Sub topic 1
Conditions: comparison operators and boolean expressions
Every if and elif statement depends on one thing: a condition. Before you write branching code, you need to know what a condition is, how Python evaluates it, and which mistakes make a condition quietly do the wrong thing. This chapter covers comparison operators and boolean expressions. Later chapters build the if, elif, and else statements on top of them.
Prerequisites
This chapter assumes you can do the following:
- Run a Python script or use the interactive interpreter (the
>>>prompt). - Use the basic data types:
int,float,str,bool,list,dict, andNone. - Call
print()and read a simple function definition.
The examples use the interpreter style. A line starting with >>> is input, and the line below it is the result.
What a condition is
A condition is any expression that Python can reduce to a truthy or falsy value. The clearest conditions are expressions that produce a bool, which is a value that is either True or False.
age = 20
print(age >= 18)
print(type(age >= 18))This prints True and then <class 'bool'>. The comparison age >= 18 is evaluated first and produces a value. That value can be printed, stored in a variable, returned from a function, or handed to an if statement.
is_adult = age >= 18
print(is_adult)Naming a condition like this is often clearer than repeating a long expression in several places.
bool is a subclass of int. True behaves like 1 and False behaves like 0, so True + True is 2. You rarely need this, but it explains why True == 1 is True.
The six comparison operators
Python has six operators that compare two values and return a bool.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| `==` | equal to | `3 == 3` | `True` |
| `!=` | not equal to | `3 != 4` | `True` |
| `<` | less than | `3 < 3` | `False` |
| `<=` | less than or equal to | `3 <= 3` | `True` |
| `>` | greater than | `4 > 3` | `True` |
| `>=` | greater than or equal to | `2 >= 3` | `False` |
Two other operator families also produce booleans: membership (in, not in) and identity (is, is not). They get their own chapter, so this chapter sticks to the six above.
Assignment versus equality
A single = assigns a value and a double == compares. Mixing them up is the classic beginner error. Python usually catches it, because assignment is a statement and cannot appear inside an if condition.
x = 5
if x = 5:
print("five")This raises SyntaxError: invalid syntax. The reverse mistake is worse because it is legal. A line such as x == 5 on its own compares and throws the result away, so x is never changed and no error appears.
x = 0
x == 5 # compares, discards the result, x is still 0
print(x) # 0How values of different types compare
== and != work on almost any pair of values. The ordering operators (<, <=, >, >=) are stricter.
- Numbers compare by value across types:
1 == 1.0isTrue, and2 < 2.5isTrue. - A string never equals a number:
"10" == 10isFalse. This is a common source of bugs with input read frominput()or a file, which is always a string. - Ordering a number against a string raises an error rather than guessing.
print("10" == 10)
try:
print(2 < "3")
except TypeError as error:
print("TypeError:", error)The first line prints False. The second raises TypeError with a message such as '<' not supported between instances of 'int' and 'str'. If your data arrives as text, convert it first, for example int(text) < 3.
Strings compare character by character using Unicode code points, so the order is not the dictionary order a person expects. Uppercase letters come before lowercase letters.
print("apple" < "banana") # True
print("Zebra" < "apple") # True, because "Z" (90) is less than "a" (97)
print("apple" < "Apple") # FalseFor case-insensitive comparison, normalize both sides, for example a.lower() == b.lower().
Sequences compare element by element and stop at the first difference. This applies to lists and tuples.
print((1, 2, 3) < (1, 2, 4)) # True
print([1, 2] == [1, 2]) # True
print([1, 2] < [1, 2, 0]) # True, the shorter prefix is smallerFloating-point comparison
Floats are stored in binary, so many decimal values are approximations. Comparing them with == can surprise you.
import math
print(0.1 + 0.2 == 0.3) # False
print(0.1 + 0.2) # 0.30000000000000004
print(math.isclose(0.1 + 0.2, 0.3)) # TrueUse math.isclose when you compare computed floats. Its default relative tolerance is 1e-09. If one value might be exactly zero, also pass an absolute tolerance, for example math.isclose(a, 0.0, abs_tol=1e-12).
A related edge case is nan ("not a number"), which is not equal to anything, including itself.
nan = float("nan")
print(nan == nan) # False
print(nan != nan) # True
print(math.isnan(nan)) # TrueUse math.isnan to detect it.
Building boolean expressions
A boolean expression combines comparisons with and, or, and not. The full rules for these operators come in a later chapter. For now you need only the evaluation order.
- Arithmetic runs first, for example
x + 1. - Comparisons run next.
notruns after comparisons.andruns afternot.orruns last.
So not binds more loosely than ==. The expression not a == b means not (a == b). Parentheses cost nothing and make your intent obvious, so add them whenever a reader might have to stop and think.
temperature = 22
raining = False
comfortable = temperature > 18 and temperature < 28 and not raining
print(comfortable) # TrueThe diagram shows the order Python follows for the condition temperature > 18 and not raining.
The right-hand side is skipped when the left side is already False. This behavior is called short-circuiting, and a later chapter explains it fully.
Common errors with conditions
These mistakes appear again and again in real code.
- Using
=instead of==. Inside anifthis is aSyntaxError. Elsewhere it silently assigns. - Comparing the wrong types.
"5" == 5isFalse. Convert input before comparing. - Testing floats for exact equality. Use
math.isclosefor computed values. - Splitting a comparison wrongly.
if color == "red" or "blue":does not mean "color is red or blue". It parses as(color == "red") or "blue", and a non-empty string is always truthy, so the condition is always true. Writecolor == "red" or color == "blue", or usecolor in ("red", "blue"). - Forgetting parentheses around mixed operators. If
not,and, andorappear together, group them explicitly.
color = "green"
print(color == "red" or "blue") # blue (truthy, wrong test)
print(color == "red" or color == "blue") # False (correct test)The first line shows the bug. The expression returns the string "blue" rather than a boolean, so an if on it would run.
Inspecting a condition before you use it
When a branch behaves unexpectedly, print the condition by itself. Reducing it to a single True or False shows you which part is wrong.
score = 83
passed = score >= 60
excellent = score >= 90
print(passed, excellent) # True FalseSplitting a long condition into named parts like this makes it easier to test and to read. Once you can predict the boolean value of every condition, writing if statements around them is straightforward.
Exercise
What does each of these expressions evaluate to, and why? (a) "10" == 10 (b) 0.1 + 0.2 == 0.3 (c) not 5 > 3 (d) if mode = "fast":
Show answer
(a) False, because a string never equals an integer. (b) False, because 0.1 + 0.2 is 0.30000000000000004 in binary floating point. Use math.isclose for the comparison. (c) False, because the comparison 5 > 3 runs first and gives True, then not turns it into False. (d) It raises a SyntaxError, because a single = is an assignment and cannot be used in a condition. Use == to compare.
Exercise
A programmer writes if answer == "yes" or "y": to accept either reply. Explain why the condition is always true, then rewrite it correctly in two different ways.
Show answer
The expression parses as (answer == "yes") or "y". The string "y" is non-empty, so it is truthy, and the or returns it when the left side is False. The condition is therefore true for any answer. Two correct versions are answer == "yes" or answer == "y" and answer in ("yes", "y").