Compare values, combine conditions with and, or and not, and branch with if, elif and else.
Why it matters
Programs become useful when they make decisions: flag a temperature that is too high, give a discount over a certain spend, reject a password that is too short, assign a letter grade. Every one of those is a condition: a question with a yes-or-no answer, followed by different code for each answer.
Booleans: True and False
A comparison produces a boolean, a value that is either True or False:
print(5 > 3) # True
print(5 == 3) # False (== asks "are these equal?")
print(5 != 3) # True (!= means "not equal")
print(4 <= 4) # True
print("cat" == "Cat") # False: comparisons are case-sensitive
The six comparison operators are ==, !=, <, <=, > and >=. Remember: a single = stores a value, a double == compares.
Combining conditions
Use and, or and not to build bigger questions:
temp = 22
humidity = 70
print(temp > 18 and temp < 26) # True: both parts are True
print(temp > 30 or humidity > 60) # True: at least one part is True
print(not temp > 30) # True: flips False to True
Python also lets you chain comparisons the way you would in maths: 18 < temp < 26 means the same as temp > 18 and temp < 26.
if, elif and else
temp = 31
if temp > 30:
print("Too hot: open the vents")
elif temp < 10:
print("Too cold: turn on the heater")
else:
print("Temperature OK")
How it works:
- Python checks the
ifcondition. If it isTrue, it runs that indented block and skips the rest. - Otherwise it checks each
elif("else if") in order and runs the first one that isTrue. - If none matched, the
elseblock runs.elifandelseare both optional.
Indentation is part of the syntax. The lines that belong to a branch are indented (four spaces is the standard). The colon at the end of the if line is required. When the indentation ends, so does the branch.
Order matters in elif chains
Because Python stops at the first true branch, put the most specific tests first:
score = 95
# Wrong order: 95 is >= 60, so this prints "D"
if score >= 60:
grade = "D"
elif score >= 90:
grade = "A"
# Right order: highest threshold first
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(grade) # A
Truthiness
if does not need a comparison. Python treats some values as "falsy": 0, 0.0, the empty string "", empty lists and None. Everything else is "truthy":
name = ""
if name:
print(f"Hello, {name}")
else:
print("Please enter your name")
This is a neat shortcut for "is it empty?", but use explicit comparisons when they are clearer, such as if count == 0:.
What about input()?
In a terminal, input("Your age: ") pauses the program and returns what the user typed, always as a string, so you would write age = int(input("Your age: ")). The in-browser runner on this site cannot pause for typing, so in the Do tab we set values directly or pass them to a function. The decision logic is exactly the same.
A worked example
A theme park ride needs riders to be at least 120 cm tall, or at least 100 cm when riding with an adult:
def can_ride(height_cm, with_adult):
if height_cm >= 120:
return True
elif height_cm >= 100 and with_adult:
return True
else:
return False
print(can_ride(130, False)) # True
print(can_ride(110, True)) # True
print(can_ride(110, False)) # False
def creates a function, a named, reusable block that takes inputs and returns a result. Module 2 covers functions properly; here it just lets us test one rule with several inputs. The whole rule also fits on one line: return height_cm >= 120 or (height_cm >= 100 and with_adult).
Common mistakes
=instead of==.if temp = 30:is aSyntaxError.- Missing colon or indentation. Every
if,elifandelseline ends with:and its block is indented. - Testing in the wrong order. In an
elifchain, the first true branch wins. if x == 1 or 2:This is always true, because2on its own is truthy. Writeif x == 1 or x == 2:orif x in (1, 2):.- Comparing text with numbers.
"10" > 9is an error. Convert first.
Quick recap
- Comparisons (
== != < <= > >=) giveTrueorFalse. and,orandnotcombine conditions.if/elif/elseruns the first branch whose condition is true.- Indentation and the colon define each branch.
- Empty and zero values are falsy; most other values are truthy.
Try it
In the Do tab you will finish two functions: one turns a score into a letter grade, the other decides whether a reading is in a safe range.