Sub topic 3
The if statement
This chapter assumes you can run Python scripts, use variables and basic types (int, float, str, bool, list, dict, None), and call print(). It also assumes you have seen comparison operators such as >= and ==. Here you will use them to control which code runs.
What an if statement does
An if statement runs a block of code only when a condition is true. A condition is any expression that Python can evaluate to True or False. If the condition is False, Python skips the block and continues with the next statement.
An if statement is what lets a program react to its data instead of running the same lines every time.
Syntax
An if statement has three parts:
- The keyword
if, followed by a condition. - A colon
:at the end of that line. - An indented block of one or more statements.
age = 20
if age >= 18:
print('adult')
print('done')This prints adult and then done. The print('done') line is not indented, so it is outside the block and always runs. Change age to 15 and only done is printed.
The standard indent is four spaces. Every statement in the block must use the same indent. The block ends at the first line that returns to the earlier indent.
The flow of control
The diagram shows what Python does when it reaches an if statement.
A block can hold many statements
A block can contain any number of statements, including other if statements.
temperature = 31
if temperature > 30:
print('Hot day')
print('Drink water')
print('Forecast checked')Both lines inside the block run together, or neither runs. Forecast checked prints in either case.
An if without else inside a function
When a function has an if with a return and no other return, the function returns None if the condition is false. Python adds that return silently.
def check_age(age):
if age >= 18:
return 'adult'
print(check_age(20))
print(check_age(10))This prints adult and then None. The second call finds the condition false, skips the block, reaches the end of the function, and returns None. This is a common source of surprises when you later use the result, for example by calling a string method on it.
Common errors
| Mistake | What Python reports |
|---|---|
| Missing colon after the condition | `SyntaxError: expected ':'` |
| No indented line after the `if` line | `IndentationError: expected an indented block after 'if' statement` |
| Inconsistent indentation inside a block | `IndentationError: unindent does not match any outer indentation level` |
| Using `=` where `==` was meant | `SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?` |
Checking your understanding
When a program does not behave as expected, work out which lines are inside the block. Look at the indentation of each line, not at what you intended. Then evaluate the condition by hand with the actual variable values.
Exercise
What does this code print? count = 3 if count > 5: print('many') print('too many') print('finished')
Show answer
It prints only finished. The condition count > 5 is False because 3 is not greater than 5, so Python skips both indented lines. The last print has no indent, so it is outside the block and always runs.
Exercise
A function contains if score >= 50: followed by an indented return 'pass', and nothing else. What does f(30) return, and why?
Show answer
It returns None. The condition is False, so the block is skipped. The function then reaches its end without a return statement, and Python returns None by default.