Control flow
Make decisions with if, repeat with for and while — and meet Python's significant whitespace.
- Branch with if / elif / else
- Iterate with for (over collections and range) and while
- Use indentation correctly — in Python, whitespace is syntax
Python expresses the three universal shapes of logic — sequence, selection, and iteration — with notably clean syntax. The rule that surprises newcomers: indentation is significant. The block belonging to a statement is defined by how far it's indented, not by braces or keywords.
Selection: if / elif / else
temperature = 22
if temperature > 30:
print("hot")
elif temperature > 15:
print("pleasant")
else:
print("cold")The colon opens a block; the indented lines below form its body. elif ("else
if") lets you chain conditions; only the first matching branch runs. Mis-indent
and you'll get an IndentationError, or — worse — code that runs but belongs to
the wrong block.
Iteration: for
A for loop walks through the items of any collection:
for name in ["Ada", "Alan", "Grace"]:
print(f"Hello, {name}")To repeat a fixed number of times, loop over range:
for i in range(3): # 0, 1, 2
print(i)Note range(3) yields 0, 1, 2 — it starts at 0 and stops before 3. That
half-open convention is everywhere in Python; it's worth internalising early.
Iteration: while
A while loop repeats as long as its condition stays true, so something inside
must eventually make it false:
count = 3
while count > 0:
print(count)
count = count - 1 # the line that guarantees terminationChanging the flow: break and continue
Two tools adjust loops mid-stream:
breakexits the loop entirely.continueskips to the next iteration.
for n in range(10):
if n == 5:
break # stop at 5
if n % 2 == 0:
continue # skip even numbers
print(n) # prints 1, 3The classic beginner bug is a while loop whose condition never becomes false.
Whenever you write one, point at the line that moves it toward stopping — and if
there isn't one, you've written an infinite loop.
Where to go next
You can now make decisions and repeat work. Combined with variables and types, that's enough to express real logic — and the foundation for the intermediate track's comprehensions.
Write sum_to(n) so it returns the sum of every integer from 1 to n (inclusive). Use a loop — the skill from this lesson.
sum_to(3) → 6sum_to(5) → 15