Free Handbook · Runs in your browser

Flow Control

if / elif / else, for and while loops traced step by step, break, continue and pass, the loop-else nobody teaches, and match statements — plus the IndentationError and the infinite loop you will write this week.

0 / 108 lessons🔥 0 day streak
ShareXLinkedIn

Module 02 · what you'll be able to do

  • Branch with if / elif / else and write conditions that read like English
  • Loop with for over any sequence, with range(), enumerate() and zip()
  • Loop with while and know exactly when to prefer it over for
  • Use break, continue, pass and the for…else clause correctly
  • Match on structure with match / case (Python 3.10+)
  • Diagnose an IndentationError and stop an infinite loop
01

if, elif, else

A block in Python is defined by indentation, not braces. The colon opens the block; every line indented under it belongs to it; the first line back at the old indentation ends it. Four spaces is the standard. This is the one rule that makes Python code look the same everywhere.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
Warm
Cart is empty
odd
Your turn
Set temperature = 36. Only one branch runs — the first true one. Then rewrite the chain with the ranges in a different order and see what breaks.
VisualizeHow an if / elif chain is evaluatedStep 1 / 5
temperature = 31
if temperature > 35:
print("Heat warning")
elif temperature > 25:
print("Warm")
else:
print("Cold")
Line 1

Bind temperature to 31.

Variables now
temperature31
All 5 steps as a table
StepLineWhat happenedVariables now
11Bind temperature to 31.temperature = 31
22Evaluate 31 > 35 → False. Skip this block entirely.
34Evaluate 31 > 25 → True. Enter this block.
45Print "Warm". Because a branch matched, every remaining elif/else is skipped without being evaluated.
57Never reached. Only one branch of a chain ever runs.
Error you will hit

IndentationError: expected an indented block after 'if' statement

python
x = 5
if x > 3:
print("big")
  File "your code", line 3
    print("big")
    ^
IndentationError: expected an indented block after 'if' statement on line 2
Why the interpreter said that

The colon promised a block and the next line was not indented, so the parser has no idea what belongs to the if. The cousin error, unindent does not match any outer indentation level, means you mixed indent widths — usually tabs and spaces from two editors.

The fix

Indent the body four spaces. Set your editor to insert spaces for Tab.

python
x = 5
if x > 3:
    print("big")
02

for loops

A Python for loop is not a counter — it is "for each item in this thing". Strings, lists, dictionaries, files and ranges are all iterable, and the loop variable takes each item in turn. When you do need numbers, range() produces them lazily.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
apple
pear
fig
0 1 2 
2 5 8 
1 apple
2 pear
Ada: 98
Linus: 87
a → 1
b → 2
Your turn
Print the multiplication table for 7 (7 × 1 … 7 × 10) using range and an f-string.
VisualizeSumming a list, one iteration at a timeStep 1 / 9
total = 0
for n in [3, 5, 9]:
total += n
print(total)
Line 1

Start the accumulator at 0.

Variables now
total0
All 9 steps as a table
StepLineWhat happenedVariables now
11Start the accumulator at 0.total = 0
22Take the first item of the list: n is 3.n = 3
33total += n → 0 + 3.total = 3
42Next item: n is 5.n = 5
533 + 5.total = 8
62Last item: n is 9.n = 9
738 + 9.total = 17
82The list is exhausted, so the loop ends. Note n still exists afterwards and holds the last value — Python does not scope loop variables.
94Print the result.
Do not modify a list while looping over it
Removing items from the list you are iterating skips elements silently. Build a new list instead ([x for x in items if keep(x)], Module 09) or loop over a copy (for x in items[:]).
03

while loops

while repeats as long as its condition is true. Use it when you do not know in advance how many iterations you need — reading until input is valid, retrying until a server answers, running a game loop. If you find yourself writing i = 0; while i < n: … i += 1, that is a for i in range(n).

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
111 steps
connected on attempt 3
Your turn
Write a while loop that doubles money = 1000 at 7% per year and counts the years until it exceeds 2000.
Error you will hit

The infinite loop (no traceback — it just never ends)

python
count = 10
while count > 0:
    print(count)
    # forgot: count -= 1
10
10
10
10
... forever. In this page the engine is stopped after 15 seconds:
"Your code did not finish within 15 seconds and was stopped."
On your machine: press Ctrl+C → KeyboardInterrupt
Why the interpreter said that

The condition count > 0 never becomes false because nothing inside the loop changes count. Every while loop needs something in its body that moves the condition toward false — or a break.

The fix

Change the state the condition depends on, every iteration.

python
count = 3
while count > 0:
    print(count)
    count -= 1
04

break, continue and pass

break leaves the loop immediately. continue skips the rest of this iteration and goes to the next. pass does nothing — it exists because a block cannot be empty, so it holds the place while you are writing. And a loop can have an else: it runs only if the loop finished without breaking — the cleanest way to write "search, and if not found".

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
1 3 5 7 
9 is not in the list
None
Your turn
Nested loops: break only leaves the innermost one. Write two nested loops and use a flag variable (or a function with return) to leave both.
Quick check

When does the else clause of a for loop run?

05

match / case (structural pattern matching)

Python 3.10 added match. It looks like a switch, but it is more: a case can match on structure — the length of a list, the keys of a dict, the type of an object — and bind variables out of it in one step. For a plain "compare one value to constants", an if-chain or a dictionary is still fine; match earns its place on nested data like API responses and commands.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
'go north'                   → moving north
'pick up sword shield'       → picking up sword, shield
'exit'                       → bye
'dance'                      → unknown command
large payment: 250
Your turn
Add a case for ["drop", item]. Then change the amount to 50 and watch the guard send it to the second case.
A bare name in a case is a capture, not a constant
case RED: does not compare against a variable named RED — it binds anything to a new name RED and always matches. To compare with a constant, qualify it: case Color.RED:, or use a literal.

Frequently asked questions

Does Python have a do-while loop?
No. The idiom is while True: with a break at the point where a do-while would test its condition.
Why does Python use indentation instead of braces?
Because every other language enforces indentation through style guides and linters anyway; Python makes the indentation the syntax so the code cannot lie about its structure. The practical cost is one new error, IndentationError, which this module covers.

Finish the Python handbook, then get hired

Sit the exam for your certificate, run your resume through the ATS checker, and see the jobs that ask for exactly this.

Check my resume
Found this course useful? Share it.
ShareXLinkedIn

Comments

0

Join the conversation. Sign in to leave a comment — we'd love to hear your thoughts.