Skip to main content

Python Logical Operators

To join conditional statements together, Python gives you three logical operators:

  • and - True only when the two statements are both true
  • or - True when at least one statement is true
  • not - Flips the result, so true becomes False and false becomes True

The and Operator

The and operator joins two conditions and demands that both of them hold. If either one fails, the whole expression is False.

Example

Checking that a is above b AND c is above a:
Prompt
Write a Python program that uses the and operator to test if a is greater than b AND c is greater than a.
Output: complete Python program

The or Operator

The or operator also joins two conditions, but it is easier to satisfy. A single true condition is enough to make the whole expression True.

Example

Checking whether a is above b OR above c:
Prompt
Write a Python program that uses the or operator to test if a is greater than b OR a is greater than c.
Output: complete Python program

The not Operator

The not operator works on one condition and turns its result into the opposite.

Example

Checking that a is NOT above b:
Prompt
Write a Python program that uses the not operator to test if a is NOT greater than b.
Output: complete Python program

Combining Multiple Operators

A single expression may contain several logical operators. Python handles them in a fixed order: not comes first, followed by and, and finally or.

Example

Using and, or and not together:
Prompt
Write a Python program that combines and, or, and not operators to check if a discount applies based on age, student status, and discount code.
Output: complete Python program

Truth Tables

These tables show the result of each operator for every pair of values:

Truth Table for the and Operator

Condition 1Condition 2Result
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Truth Table for the or Operator

Condition 1Condition 2Result
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Using Parentheses for Clarity

When an expression mixes several logical operators, parentheses show what you mean and decide what gets evaluated first.

Example

Parentheses in a longer condition:
Prompt
Write a Python program that uses parentheses with logical operators to check weather and weekend conditions for outdoor activities.
Output: complete Python program

More Examples

Example

Checking login details:
Prompt
Write a Python program that checks username, password, and verification status using logical operators and prints login result.
Output: complete Python program

Example

Making sure a score falls within a range:
Prompt
Write a Python program that uses the and operator to check if a score is within a valid range (0-100).
Output: complete Python program