Simple comparisons can only check one thing at a time. But real decisions often involve multiple conditions — a rollercoaster might need you to be both tall enough and old enough. To combine conditions in Python, you use logical operators: and, or, and not.
The Three Logical Operators
| Operator | Meaning | Result is True when... |
|---|---|---|
and | Both conditions | Both sides are True |
or | Either condition | At least one side is True |
not | Opposite | The condition is False |
The and Operator
and requires both conditions to be True for the overall result to be True:
age = 15
height = 140
if age >= 12 and height >= 130:
print("You can ride!")
else:
print("Sorry, you cannot ride.")
If either condition is False, the whole expression is False and the person cannot ride.
Truth table for and:
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
The or Operator
or only requires one condition to be True:
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("Weekend! No school.")
else:
print("Weekday. Time for school.")
Truth table for or:
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
or is inclusive — it is True if one or both sides are True. In everyday English "or" sometimes implies "but not both", but in programming or always means "at least one".
The not Operator
not flips a Boolean value:
is_logged_in = False
if not is_logged_in:
print("Please log in.")
not False is True, so the message displays. not True would be False.
not is useful for making conditions read more naturally. if not is_empty: is clearer than if is_empty == False:.
Combining Multiple Operators
You can combine and, or, and not in the same expression:
score = 85
is_member = True
if score >= 80 and is_member or score >= 95:
print("Prize awarded!")
Be careful with operator precedence: not binds most tightly, then and, then or. Use brackets to make your intentions explicit and avoid subtle bugs: if (score >= 80 and is_member) or score >= 95: is much clearer.
A Practical Example
username = input("Username: ")
password = input("Password: ")
valid_user = username == "admin"
valid_pass = password == "secure99"
if valid_user and valid_pass:
print("Access granted.")
elif valid_user and not valid_pass:
print("Incorrect password.")
else:
print("Unknown username.")
Practice Problems
What does this expression evaluate to? (5 > 3) and (10 < 8)
Show answer
Write a condition using logical operators that checks whether a number n is between 1 and 100 inclusive.