Comparison and logical operators
Programs make decisions by asking questions: is the user old enough? Is the password long enough? Each question is a comparison whose answer is True or False.
Comparison operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal to | 5 != 3 | True |
< | less than | 3 < 5 | True |
> | greater than | 3 > 5 | False |
<= | less than or equal | 5 <= 5 | True |
>= | greater than or equal | 4 >= 5 | False |
Python
age = 17
print(age >= 18)
print(age == 17)
print(age != 17)Chained comparisons
Python lets you chain comparisons the way you would write them in maths:
Python
temperature = 22
print(18 <= temperature <= 25) # same as 18 <= t and t <= 25
x = 5
print(1 < x < 10 < 100)Logical operators
Combine conditions with and, or and not:
| Operator | True when |
|---|---|
a and b | both are true |
a or b | at least one is true |
not a | a is false |
Python
age = 20
has_ticket = True
is_vip = False
print(age >= 18 and has_ticket) # both must be true
print(has_ticket or is_vip) # one is enough
print(not is_vip)Short-circuit evaluation
Python stops evaluating as soon as it knows the answer. With and, if the left side is false, the right side is never checked:
Python
items = []
# safe: len(items) > 0 is False, so items[0] is never evaluated
print(len(items) > 0 and items[0] == "apple")Without short-circuiting, items[0] would crash on an empty list. Putting the "safety check" first is a common, useful pattern.
Precedence
not binds tightest, then and, then or. So a or b and c means a or (b and c). Use brackets to make intentions clear:
Python
print(True or False and False) # True or (False and False)
print((True or False) and False)Finished this lesson?Mark it complete to earn +20 XP and move your progress on.