Data types · 8 / 29 Theory

Comparisons and logical values

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

OperatorMeaningExampleResult
==Equal to3 == 3True
!=Not equal to3 != 4True
<Less than3 < 2False
>Greater than3 > 2True
<=Less than or equal3 <= 3True
>=Greater than or equal2 >= 3False

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.0 is True.
  • A text is never equal to a number: "1" == 1 is False.
  • Texts are compared letter by letter, distinguishing upper and lower case: "abc" < "abd" is True, 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:

OperatorMeaningExampleResult
andTrue if both areTrue and FalseFalse
orTrue if either isTrue or FalseTrue
notInverts the valuenot TrueFalse
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.