Sub topic 3
The if statement
The if statement runs a block of code only when a condition holds. It is the base of every decision in Python, and else and elif build on it in later chapters. This chapter covers how if is evaluated, how blocks work, and the errors you will meet most often.
Prerequisites
This chapter assumes you can do the following:
- Run a script or use the interactive interpreter.
- Use variables and the basic types:
int,float,str,bool,list,dictandNone. - Call
print()and define a simple function.
The basic shape
An if statement has a keyword, a condition, a colon, and an indented block.
temperature = 31
if temperature > 30:
print('It is hot')
print('Drink water')
print('Done')This prints three lines. The comparison temperature > 30 is True, so Python runs both indented lines. print('Done') is not indented, so it is outside the block and runs every time.
If you change temperature to 20, only Done is printed. When the condition is false and there is no other branch, Python skips the block and continues with the next statement. No error occurs and nothing is printed for the skipped block.
How Python evaluates an if
Python follows these steps:
- It evaluates the expression after
if. - It converts the result to
TrueorFalse. - If the result is
True, it runs the indented block from top to bottom. - Either way, it then continues with the first line that is not part of the block.
The diagram has two paths and they rejoin. An if without else never leaves your program in a different place afterward. It only decides whether the block runs.
What can be a condition
The condition can be any expression. Python does not require a bool. It asks each value whether it counts as true. The following example uses three different kinds of expression.
name = 'Ada'
scores = [90, 85]
if name == 'Ada':
print('comparison produced True')
if scores:
print('a non-empty list counts as true')
if len(scores) > 1 and scores[0] > 80:
print('two operators combined into one condition')The most common conditions are comparisons: ==, !=, <, <=, >, >=. Each one produces a bool. Other values follow truthiness rules. Empty collections, 0, 0.0, '' and None count as false. Almost everything else counts as true. A later chapter covers truthiness in detail. For now, remember that the condition is converted with the same rules as the built-in bool() function.
print(bool(0))
print(bool('0'))
print(bool([]))
print(bool([0]))This prints False, True, False, True. The string '0' is not empty, so it counts as true. The list [0] has one element, so it also counts as true.
Colons and indentation
Python marks a block with a colon at the end of the if line and a consistent indent on the lines that follow. It has no braces or end keyword. The indentation is the structure.
The rules are:
- Every line in the block must start with the same indentation.
- The block must contain at least one statement.
- The standard is four spaces per level. Do not mix tabs and spaces in one file.
- A block ends at the first following line with less indentation.
Because indentation defines membership, moving one line changes what the program does.
count = 0
total = 0
if count > 0:
total = 100
print('adding')
print('total is', total)Here print('total is', total) sits at the left margin, so it always runs. If you indent it by four spaces, it only runs when count > 0. The program then prints nothing for count = 0.
A block that does nothing
A block cannot be empty. When you need a placeholder, use pass, which does nothing.
debug = False
if debug:
pass # TODO: add logging here laterA comment alone is not a statement, so a block that holds only a comment raises an IndentationError.
Several ifs in a row
Each if is its own decision. Python tests every one in order, and each can run its block.
age = 70
has_ticket = True
if age >= 65:
print('senior discount')
if has_ticket:
print('admit one')
if age < 18:
print('child discount')This prints senior discount and admit one. The first two conditions are true, so both blocks run. The third is false, so it is skipped. If you want exactly one block to run out of several, use elif. A later chapter covers it.
Variables set inside an if
An if block does not create a new scope. A name assigned inside the block still exists after it. The problem is that the name only exists if the block actually ran.
def label_for(score):
if score >= 50:
result = 'pass'
return result
print(label_for(80))
print(label_for(20))label_for(80) returns 'pass'. label_for(20) raises UnboundLocalError, because result was never assigned. There are two usual fixes. You can assign a default before the if, or you can handle the other case with else.
def label_for(score):
result = 'fail'
if score >= 50:
result = 'pass'
return result
print(label_for(80))
print(label_for(20))This version prints pass and then fail.
The one-line form
Python allows a short body on the same line as the condition.
x = 5
if x > 3: print('big')This is legal, but most style guides, including PEP 8, discourage it. You cannot put a second statement on the line in a readable way, and adding one later means rewriting the line. Use the indented form.
Common errors
Most beginners' mistakes with if produce one of the messages below. The exact wording differs between Python versions. The messages here are from Python 3.10 and later.
| Mistake | Typical error | Fix |
|---|---|---|
| Missing colon: `if x > 3` | `SyntaxError: expected ':'` | Add `:` at the end of the line |
| No indented body | `IndentationError: expected an indented block after 'if' statement` | Indent the body, or use `pass` |
| Inconsistent indent in a block | `IndentationError: unindent does not match any outer indentation level` | Use the same indentation on every line of the block |
| Mixed tabs and spaces | `TabError: inconsistent use of tabs and spaces in indentation` | Use four spaces everywhere |
| `=` instead of `==`: `if x = 3:` | `SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?` | Write `if x == 3:` |
| Name assigned only inside the block | `UnboundLocalError` or `NameError` | Assign a default before the `if` |
The = mistake is caught as a syntax error. A related mistake is not caught. Writing if x == 3 or 4: is valid Python, but it does not mean "x is 3 or 4". It parses as (x == 3) or 4, and 4 is always true. The condition is therefore always true. Write if x == 3 or x == 4: or if x in (3, 4): instead.
Comparing floats
Floating-point numbers store approximate values, so == can fail unexpectedly.
import math
a = 0.1 + 0.2
if a == 0.3:
print('equal by ==')
if math.isclose(a, 0.3):
print('equal by isclose')Only equal by isclose is printed, because 0.1 + 0.2 is 0.30000000000000004. Use math.isclose() when comparing computed floats.
Summary
if condition:followed by an indented block runs the block only when the condition counts as true.- Python converts any condition to
TrueorFalseusing truthiness rules. - Indentation and the colon define the block. The block must hold at least one statement.
- Consecutive
ifstatements are independent, and each can run. - Names assigned inside a block may be undefined if the block did not run.
- Most
iferrors are a missing colon, bad indentation, or=used in place of==.
Exercise
What does this program print, and why? x = 4 if x > 3: print('A') if x > 10: print('B') print('C') if x: print('D')
Show answer
It prints A, C and D on separate lines. x > 3 is true, so A is printed. x > 10 is false, so the block with B is skipped. print('C') is at the left margin, so it always runs. The last if x: tests the truthiness of 4, which is true, so D is printed.
Exercise
This function should return 'positive' for numbers above zero. For other numbers it should return 'not positive'. It fails for some inputs. Which inputs fail, and how do you fix it without using else? def sign(n): if n > 0: text = 'positive' return text
Show answer
It fails for any n that is 0 or negative. The block is skipped, so text is never assigned, and return text raises UnboundLocalError. Assign a default before the if: set text = 'not positive' first, then change it to 'positive' inside the if block.