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
rate = 0.115if 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.
rates = [0.10, 0.115, 0.125, 0.13, 0.135]# Most common: iterate valuesfor r in rates:print(f'{r:.2%}')# When you need the index toofor i, r in enumerate(rates):print(f'Year {i+1}: {r:.2%}')# Range — for countingfor i in range(5): # 0, 1, 2, 3, 4print(i)
while loops — when you don't know how many iterations
balance = 10000rate = 0.10years = 0while balance < 20000:balance *= (1 + rate)years += 1print(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.
if not rates: # True if the list is emptyprint('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()).