Making decisions with if
🌍 In real life. Before you leave home, you might think: "If it's raining, take an umbrella." On a dry day you skip that step, but either way you still leave home. One step depends on a question; everything else happens as usual.
Programs make choices like this all the time, with if.
The idea in one sentence: if runs its indented block only when its condition is True, and either way the program carries on below.
Its words:
- condition: a question with a True or False answer, like
temperature > 30 - block: the lines that belong to the
if, indented underneath it - indentation: the spaces at the start of a line; 4 spaces is the Python habit
- the colon
:at the end of theifline, which says "a block starts here"
Step by step:
- Python works out the condition.
- If it's True, Python runs the indented block, line by line.
- If it's False, Python skips the whole block.
- Either way, it carries on with the first line that isn't indented.
temperature = 32
if temperature > 30:
print("Hot!")
print("Drink water")
print("Done")Now try a cooler day. The condition is False, so Python skips the whole indented block:
temperature = 20
if temperature > 30:
print("Hot!")
print("Drink water")
print("Done")How Python knows where the block ends. Many languages use { } around a block. Python uses indentation instead: every line indented under the if belongs to it, and the first line back at the left edge is outside it. That's why the spaces matter so much in Python.
Your conditions are the comparisons from Chapter 2: ==, !=, <, >, plus <= (less than or equal to) and >= (greater than or equal to).
age = 18
if age >= 18:
print("You can vote")
if age == 18:
print("Just old enough!")Mistakes and edge cases.
- A missing colon.
if x > 3givesSyntaxError: expected ':'. - A missing indent. The block's lines must be indented: otherwise
IndentationError: expected an indented block after 'if' statement on line 2. - = in a condition.
if x = 5:givesSyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?. Asking is==. - Uneven indents. A block's lines must all use the same number of spaces, or you get
IndentationError: unindent does not match any outer indentation level. - Comparing text with a number.
"5" == 5isFalsewithout any error, so convertinput()answers before comparing them.
The two programs below show the first two errors:
x = 5
if x > 3
print("big")x = 5
if x > 3:
print("big")Quiz
What does this print?
x = 10 if x > 5: print("A") print("B")And now?
x = 2 if x > 5: print("A") print("B")What does
<=mean?- Less than or equal to
- Less than
- Equal to
Which line has a mistake?
n = 4 if n == 4 print("four")What does this print?
n = 7 if n % 2 == 1: print("odd")
Coding tasks
Ask for a whole number. If it is greater than 100, print
Big number!. Always printDoneat the end.Ask for a password. If it is exactly
open sesame, printWelcome!. Otherwise, print nothing.