Comparing values is the basis for a program to make decisions. Every comparison results in a logical value (bool): True or False. In the next lesson you will use them in conditions; here you will learn how to build them.
Comparison operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 3 == 3 | True |
!= | Not equal to | 3 != 4 | True |
< | Less than | 3 < 2 | False |
> | Greater than | 3 > 2 | True |
<= | Less than or equal | 3 <= 3 | True |
>= | Greater than or equal | 2 >= 3 | False |
Mind the difference: = assigns a value to a variable and == compares two values.
age = 20 # assignment
print(age == 20) # True (comparison)
print(age >= 18) # True
Comparing numbers, texts and different types
- An integer and a decimal with the same value are equal:
1 == 1.0isTrue. - A text is never equal to a number:
"1" == 1isFalse. - Texts are compared letter by letter, distinguishing upper and lower case:
"abc" < "abd"isTrue, and so is"Z" < "a"(capital letters come first).
Chained comparisons
Python lets you check a range like in maths:
x = 7
print(1 < x < 10) # True
print(5 < 3 < 10) # False
Logical operators: and, or, not
They are used to combine logical values:
| Operator | Meaning | Example | Result |
|---|---|---|---|
and | True if both are | True and False | False |
or | True if either is | True or False | True |
not | Inverts the value | not True | False |
age = 20
print(age >= 18 and age < 65) # True
print(age < 18 or age >= 65) # False
print(not age == 20) # False
If you mix several, the order of priority is not, then and and finally or: True or False and False is True, because False and False is evaluated first. When in doubt, use parentheses.
Comparing with None
To know whether something is None you use is, not ==:
result = None
print(result is None) # True
print(result is not None) # False
Values that count as true or false
Any value can be used as a condition: 0, "", [] and None are False, and the rest are True. Careful: the text "0" is true, because it is not empty.
print(bool(0)) # False
print(bool("0")) # True
print(bool("")) # False
print(bool(" ")) # True (it has a space)
Practice in the exercises about the comparison table and palindromes.