Control flow lets a program choose which code to run and repeat work, instead of running top to bottom once.
Boolean conditions
- Comparisons produce
True/False:<,>,==(equal?),!=(different?),<=,>=. ==compares;=assigns.if x = 5:is aSyntaxError.- Combine with
and(both),or(either),not(flip).
if / elif / else
if condition:runs its indented block only when the condition isTrue.elifadds more cases checked in order;elseis the catch-all.- Python runs the first true branch and skips the rest.
- Indentation (4 spaces) is the grouping — no braces. Wrong indentation is an error.
score >= 90 ? --True--> "A"
|False
score >= 80 ? --True--> "B"
|False
score >= 70 ? --True--> "C"
|False
--------> "below C"
for loops
- Runs the block once per item:
for item in sequence:. One pass is an iteration. range(n)gives0 .. n-1;range(start, stop, step)stops beforestop; negative step counts down.rangeis O(1) space — it yields numbers on demand, not a list.enumerate(seq)unpacksindex, valueeach pass, so no manual counter.
while loops
- Repeats as long as the condition stays true; checked before each pass.
- The block must move the condition toward
False(e.g.count = count - 1). - Forgetting that update = infinite loop (the classic
whilebug);Ctrl+Cstops a hung program.
break, continue, nesting
breakexits the loop immediately.continueskips the rest of the current iteration, jumps to the next.- Inner loop runs fully on each outer pass; two loops over size n is O(n squared).
Gotchas
rangestops one early:range(1, 5)=1,2,3,4. Go one past to include a value.range(5, 1)yields nothing, so the loop body never runs — check bounds.- Don’t add/remove items from a list while looping over it; loop a copy or build a new list.
- In a branching test like FizzBuzz, check the combined case (
% 3 and % 5) first.