Making decisions
So far every line of your programs has run. Now your code will choose what to do based on the data it sees.
Comparisons
Comparison operators produce a boolean, True or False:
5 == 5 # True (equal)
5 != 3 # True (not equal)
5 < 3 # False
5 >= 5 # True
"a" < "b" # True (alphabetical order)
Watch out: = assigns a value, == compares two values.
if
temperature = 31
if temperature > 30:
print("It is hot.")
print("Drink some water.")
print("This always runs.")
The line ending in a colon starts a block. Everything indented underneath (use four spaces) belongs to that block and only runs when the condition is true. Indentation is not decoration in Python: it is how Python knows where the block ends.
else and elif
score = 72
if score >= 80:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(grade) # B
Python checks each condition from the top and runs the first block whose condition is true, then skips the rest. else catches everything left over.
and, or, not
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("Come in.")
if age < 13 or age > 65:
print("Discount applies.")
if not has_ticket:
print("Buy a ticket first.")
Python also lets you chain comparisons the way you would in maths: if 0 <= x < 10:.
Truthiness
Any value can be used as a condition. Zero, empty strings, empty lists and None count as false; almost everything else counts as true.
name = input("Name: ")
if name:
print(f"Hi {name}")
else:
print("You did not type anything.")
Exercises
1. Even or odd
Ask the user for a whole number and print whether it is even or odd.
Show answer
n = int(input("Number: "))
if n % 2 == 0:
print("even")
else:
print("odd")
A number is even when dividing by 2 leaves no remainder.
2. Leap years
A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Write the condition. Check it with 2024 (leap), 1900 (not leap) and 2000 (leap).
Show answer
year = int(input("Year: "))
leap = (year % 4 == 0 and year % 100 != 0) \
or year % 400 == 0
print(leap)
3. Spot the bug
This program prints "C" for a score of 95. Why?
if score >= 60:
print("C")
elif score >= 90:
print("A")
Show answer
Python runs the first true branch only. 95 is already at least 60, so the first branch wins. Check the strictest condition first: put >= 90 above >= 60.