Skip to content
Module 04 of 1245 min readBeginner

Control flow: if, for, while

Conditionals, iteration, and the truthiness rules that surprise everyone in their first week.

33%

Listen along

Read “Control flow: if, for, while” aloud

Plays in your browser using on-device text-to-speech — nothing leaves the page.

Learning objectives

By the end of this module, you should be able to:

  • 01Write if / elif / else chains and ternary expressions idiomatically
  • 02Use enumerate() and zip() instead of manual index loops
  • 03Understand truthiness: when an empty list, empty dict, 0, or None evaluates False
  • 04Apply break, continue, and the rarely-known for-else clause

Conditional logic, loops, and the comparison operators that drive them. Python's syntax is clean enough that control flow rarely surprises — but the truthiness rules catch every beginner at least once.

if / elif / else

python
rate = 0.115
if rate > 0.13:
stance = 'tight'
elif rate > 0.10:
stance = 'neutral'
else:
stance = 'loose'

for loops — iterate over anything

Python's for loop is a 'for-each' over an iterable. There is no 'for i = 0; i < n; i++' style — you iterate over a sequence directly.

python
rates = [0.10, 0.115, 0.125, 0.13, 0.135]
# Most common: iterate values
for r in rates:
print(f'{r:.2%}')
# When you need the index too
for i, r in enumerate(rates):
print(f'Year {i+1}: {r:.2%}')
# Range — for counting
for i in range(5): # 0, 1, 2, 3, 4
print(i)

while loops — when you don't know how many iterations

python
balance = 10000
rate = 0.10
years = 0
while balance < 20000:
balance *= (1 + rate)
years += 1
print(f'Doubled in {years} years') # 8 years (the rule of 72 in code)

Truthiness — the rules that catch beginners

Python evaluates these as False: False, None, 0, 0.0, empty string '', empty list [], empty dict {}, empty tuple (). Everything else is True.

python
if not rates: # True if the list is empty
print('No data')
else:
print(f'{len(rates)} rates loaded')

break, continue, else

break exits the loop. continue skips to the next iteration. The little-known else clause on a for loop runs only if the loop completed without break — useful for search-and-act patterns.

Prefer comprehensions to loops

If your loop is just building a list/dict/set, use a comprehension (covered in module 6). They are more idiomatic, more readable, and slightly faster.

Exercise

Sum all the rates in a list using a for loop (without using sum()).

Key takeaways

  • Python's for loop is for-each — there is no C-style for(;;) syntax
  • Truthiness: False, None, 0, 0.0, '', [], {}, () are all False — everything else is True
  • enumerate(seq) gives (index, value) pairs; zip(a, b) gives parallel iteration
  • Prefer list comprehensions to manual loops when you're building a list

Further reading

  1. 01
  2. 02
  3. 03

    Effective Python: 90 Specific Ways to Write Better Python

    Brett Slatkin · Addison-Wesley · 2019

Loading progress…
LeadAfrikPublic Economics Hub