Decisions are where a program stops being a list of steps and starts having real behaviour. The difference between a readable conditional and a tangled one is mostly about order. Python gives you if, elif, and else with very little fuss, and since version 3.10 it gives you match as well. This lesson covers the syntax, the truthiness rules that decide what counts as true, and the habits that stop a chain of branches from turning into a thicket.
This is the first lesson in the Python if-else and Loops module, and the next lesson in this module is about "Comparison and Logical Operators in Real Conditions".
How do you write an if statement in Python?
Remember three things and you will not get them wrong. A condition ends with a colon, the body of the statement is defined by indentation, and there are no braces anywhere. The elif and else parts are both optional, and only one branch in a chain ever runs, which is the first one whose condition turns out to be true.
def grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
else:
return 'F'
for value in (95, 83, 71, 60):
print(f'{value:>3} -> {grade(value)}')
Two things about that chain are worth understanding properly. It stops at the first match, so the order of the conditions is the logic of the whole function. And each branch ends with a return, so the else is not strictly necessary, even though it is still the clearest way to say "and nothing else matched".
Because indentation carries the meaning in Python, one stray space changes the program. The habit that keeps editors honest is four spaces per level, never tabs, and letting your editor handle the indentation for you.
What counts as true?
Python does not ask you for a boolean in a condition. Any value can be tested, and it is turned into a boolean behind the scenes. The rule is short and easy to remember. Empty things are false, and everything else is true. Zero, the empty string, an empty container, and None are all falsy, and every other value is truthy.
values = [0, 1, -1, 0.0, 0.1, '', '0', 'False', [], [0], {}, None, True, False]
for value in values:
print(repr(value), '-> bool:', bool(value))
Look closely at two of those results. The non-empty string '0' is truthy, and so is the string 'False', because the group of characters is not empty. A list that holds a zero is truthy as well, because the list itself is not empty. Only a container that is completely empty is false.
That is why if value == True: is a mistake that you should avoid. It works by accident for real booleans, but it also quietly accepts 1, and it rejects any truthy object that is not literally True. Write if value: instead, or if value is True: when you really need to check the exact boolean object.
How do you write conditions that read like English?
Put the most specific case first and the general case last. A chain that checks score >= 90 before score >= 80 reads like the rules of a game. A chain that checks score >= 80 first makes the ninety branch unreachable, and that bug stays invisible until somebody reports that nobody has ever received an A.
The second habit is to test for a missing value with is None instead of == None. Comparing for equality asks whether two objects hold the same value, and a class is free to answer that question in surprising ways. Identity asks whether both names point at the same object, and that is exactly what you mean when you are checking for something that is not there.
value = None
print('value is None ->', value is None)
print('value == None ->', value == None)
count = 1
print('count == True ->', count == True)
print('bool(count) ->', bool(count))
flag = True
print('flag is True ->', flag is True)
print('flag is not None ->', flag is not None)
The third habit keeps the body of a branch short. Handle the special case first and return early. Instead of wrapping the main path in an else block four levels deep, you deal with the odd case, you return, and the rest of the function sits at the left margin where it is easy to read. Flat code is easier to read, easier to test, and easier to delete later.
When should you use match instead of if and elif?
Python 3.10 added the match statement. It picks a branch based on the shape of a value instead of on a list of separate conditions. It is a real improvement when you are handling several kinds of structured input, and it is not an improvement at all when you are only checking a range of numbers.
def describe(command):
match command:
case {'action': 'quit'}:
return 'shutting down'
case ('go', direction):
return 'going ' + direction
case str() as text:
return 'unknown text command: ' + text
case _:
return 'unknown command'
print(describe({'action': 'quit'}))
print(describe(('go', 'north')))
print(describe('fly'))
Each case tries to match the shape of the value, and the first one that matches wins. The dictionary pattern checks for a specific key and pulls its value out at the same time, so you do not need the dictionary lookup that you would otherwise write. The last case _ is the catch-all, and you should add it if you want every possible input to return something instead of None.
There are two cautions. match is not a general switch, and a chain of if statements with simple comparisons is usually clearer than a match with one arm. And you cannot fall through from one case to the next. If several cases should run, put them into one pattern or write them as separate branches.
Why do float comparisons bite?
Because a float keeps an approximation. The approximation for 0.1 plus the approximation for 0.2 is not the approximation for 0.3, so comparing them with == fails in a way that looks like a maths mistake but is really a storage problem.
import math
left, right = 0.1 + 0.2, 0.3
print('0.1 + 0.2 == 0.3 ->', left == right)
print('isclose ->', math.isclose(left, right))
print('difference ->', abs(left - right))
print('within tolerance ->', abs(left - right) < 1e-9)
Use math.isclose() when you compare floats that you calculated. Use an explicit tolerance when you want to write the test yourself. This rule applies to any value that you worked out and not just to sums, and it is one of the differences between code that works on your machine and code that works on your customer's machine.
Your turn: rewrite a decision tree
- Write a function
shipping_cost(weight_kg, is_express)that returns a cost. Shipping is free over 20 kg, it is discounted over 10 kg, express adds a surcharge, and anything invalid returnsNone. - Now restructure it with guard clauses. Each special case returns right away, and the normal path stays at the left margin. Print both versions and check that they agree for a table of test values.
- Add a check for a negative weight that returns
Nonebefore any cost is calculated. Use<and not==. - Rewrite the whole thing with
match, using a tuple pattern for the arguments. Keep both versions in the file so that you can compare them side by side. - Finally, write one condition using
is Noneand another one using== Noneagainst a value that might beNone. Add a comment that explains why the first one is the safer habit.
Decision checklist
- Conditions end with a colon, and the body is defined by indentation and never by braces.
- Only one branch of a chain runs, so order the branches from the most specific to the most general.
- Test emptiness instead of equality with
True, and check for missing values withis None. - Keep branches short and handle special cases with early returns, so that the main path stays flat.
- Use
matchwhen you are dispatching on the shape of structured values, and not for simple comparisons. - Compare calculated floats with
math.isclose()and never with==.