Chapter 3

Control Flow

3.0 Intro · 3.1 Conditionals · 3.2 Iteration

← → or Space to navigate · F for fullscreen

What Changes in Chapter 3

  • Until now, code mostly ran top-to-bottom.
  • Control flow lets a program choose paths and repeat work.
  • The two core patterns are selection and iteration.

The practical question is: which statement should run next?

Sequence, selection, and iteration control structures

Control-Flow Families

Type Statement Role in Python programs
Conditional if / else Choose between branches based on a Boolean condition.
Conditional elif Add another tested branch in a chain.
Looping for Repeat once for each item in an iterable.
Looping while Repeat while a condition remains true.
Looping while True + break Repeat until an internal stopping condition is reached.
Jump/control break Exit the nearest loop immediately.
Jump/control continue Skip the rest of this iteration and start the next one.
Jump/control return Leave a function and send a value back to the caller.

Python does not use goto, and this chapter does not cover match / case.

Chapter Route

Notebook Main job Students should be able to
0300-control-flow Big picture Explain selection vs. iteration.
0301-conditionals Branching Write if, else, elif, nested conditions, and conditional expressions.
0302-iteration Repetition Choose among for, while, break, continue, and accumulators.

3.1 Conditionals

Boolean expressions · branches · chained decisions · nested decisions · conditional expressions

Conditional Forms

Form Syntax Use when
Conditional execution if A block may or may not run.
Alternative execution if / else Exactly one of two branches should run.
Chained conditional if / elif / else More than two outcomes are possible.
Nested conditional if inside if A second decision depends on the first.
Conditional expression A if test else B Choosing between two simple values.
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

Conditions are checked from top to bottom. The first true branch wins.

Boolean Expressions Feed Branches

x = 5

if x > 0:
    print("x is positive")
num = 12

if num % 2 == 0:
    print("even")
else:
    print("odd")
  • A Boolean expression evaluates to True or False.
  • Comparison operators create Boolean values.
  • Logical operators combine tests: and, or, not.
  • Indentation defines the branch body.

% appears here only as an operator used in a condition. The operator itself belongs in Chapter 2.

Trace a Branch Before You Run It

score = 78
late = True

if score >= 90:
    label = "strong"
elif score >= 70 and not late:
    label = "passing"
elif score >= 70:
    label = "late pass"
else:
    label = "revise"

Trace:

  1. score >= 90 is False.
  2. score >= 70 and not late is False.
  3. score >= 70 is True.
  4. Python assigns "late pass" and skips the final else.

For an if / elif chain, only the first true branch runs.

Boolean Pitfalls to Catch Early

# Problem: always true for most values
if status == "new" or "open":
    process_ticket()

# Better
if status == "new" or status == "open":
    process_ticket()
# Problem: equality vs. assignment
if count = 0:
    print("empty")

# Better
if count == 0:
    print("empty")

Each side of and or or should usually be a complete Boolean expression.

Nested vs. Combined Conditions

if username == "admin":
    if password == "secret":
        print("Access granted")
    else:
        print("Wrong password")
else:
    print("Unknown user")
if username == "admin" and password == "secret":
    print("Access granted")
if 0 < x < 10:
    print("single digit")

Nest when decisions genuinely depend on prior branches. Combine tests when the condition remains readable.

Conditional Expressions

Use a conditional expression when the whole decision is a simple value choice.

age = 20

if age >= 18:
    status = "adult"
else:
    status = "minor"
age = 20

status = "adult" if age >= 18 else "minor"
label = "even" if n % 2 == 0 else "odd"

Use this form for compact assignments, not for large blocks of work.

Conditional Expression Decision Test

Use a conditional expression when all three are true:

  • You are choosing between two values.
  • Each value expression is short.
  • The condition reads clearly in the middle.

When the branches do work, use a normal if / else block.

# Good: value choice
fee = 0 if total >= 50 else 7.99
# Too much work for one expression
if total >= 50:
    email = "free-shipping"
    fee = 0
else:
    email = "standard-shipping"
    fee = 7.99

3.2 Iteration

iterables · for patterns · while patterns · loop control · accumulators

Iterables and Iterators

fruit = ("apple", "banana", "cherry")

itr = iter(fruit)

print(next(itr))  # apple
print(next(itr))  # banana
print(next(itr))  # cherry
Term Meaning
Iterable Object that can provide values one at a time.
Iterator Object that remembers the current position.
iter() Requests an iterator from an iterable.
next() Pulls the next value from an iterator.

A for loop uses this machinery automatically.

for Loop Patterns

Pattern Typical syntax Iterates over Best use case
Basic for-each for x in collection: Elements Processing values directly
range() counting for i in range(n): Numbers Counting and fixed repeats
Index-based for i in range(len(lst)): Positions Updating by index
enumerate() for i, x in enumerate(lst): Index + value Cleaner indexed loops
Nested loop for x in A: for y in B: Combinations Tables, grids, matrices
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

for i, fruit in enumerate(["apple", "banana"]):
    print(i, fruit)

Choosing the Right for

# Direct iteration
for amount in rainfall:
    print(amount)
# Index-based update
for i in range(len(numbers)):
    numbers[i] *= 2
# Parallel sequences
for name, score in zip(names, scores):
    print(name, score)
# Dictionary items
for name, score in scores.items():
    print(name, score)

Choosing Between for and while

Situation Prefer Why
Process every item in a list, string, file, or dictionary for The iterable already knows what the next value is.
Repeat a known number of times for with range() The count is fixed before the loop starts.
Stop based on user input or changing state while The number of repetitions is not known in advance.
Keep asking until valid data arrives while True + break The stopping test belongs inside the loop.
while True:
    response = input("Enter yes or no: ")

    if response in ["yes", "no"]:
        break

Start with the stopping rule, then choose the loop form.

Nested Loops

for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end=" ")
    print()
matrix = [
    [1, 2, 3],
    [4, 5, 6],
]

for row in matrix:
    for value in row:
        print(value)

The inner loop completes once for each value produced by the outer loop.

while Loop Patterns

Type Controlled by Ends when Best for
Counting while Number condition Condition becomes false Repetition with counters
Sentinel while Special value Sentinel is entered User input loops
while True break break executes Menus, games, event loops
times = 0

while times < 3:
    print("Hello!")
    times += 1

Every while loop needs a realistic path to stopping.

Sentinel and while True

total = 0
value = int(input("Number? "))

while value != -1:
    total += value
    value = int(input("Number? "))
total = 0

while True:
    value = int(input("Number? "))

    if value == -1:
        break

    total += value

Avoiding Infinite Loops

# Problem: counter never changes
count = 0

while count < 3:
    print(count)
# Better: loop state moves
count = 0

while count < 3:
    print(count)
    count += 1

Check every while loop for:

  • an initialized state variable
  • a condition that can become false
  • an update that moves toward stopping
  • a plan for invalid or unexpected input

If the loop condition depends on a variable, the loop body usually needs to update that variable.

Loop Control: pass vs. continue

Feature pass continue
Meaning Do nothing. Skip to the next iteration.
Where allowed Loops, functions, classes, if statements. Only inside loops.
Flow effect Continues with the next statement. Jumps back to the loop header.
Main use Placeholder for unfinished code. Skip selected items.
if x < 0:
    pass
for n in range(10):
    if n % 2 == 0:
        continue
    print(n)

Accumulator Pattern

rainfall = [0.2, 0.0, 1.3, 0.4]

total = 0
for amount in rainfall:
    total += amount

print(total)
wet_days = 0
for amount in rainfall:
    if amount > 0:
        wet_days += 1

print(wet_days)

Set the accumulator before the loop. Update it inside the loop. Use it after the loop.

Accumulators Can Do More Than Sum

scores = [88, 72, 95, 61]

passing = 0
for score in scores:
    if score >= 70:
        passing += 1
labels = []
for score in scores:
    labels.append("pass" if score >= 70 else "revise")
Goal Initial value Loop update
Total 0 total += value
Count 0 count += 1
Product 1 product *= value
Collection [] items.append(value)

Name the accumulator for the result it will hold after the loop.

Mini Activity: Predict the Path

temperatures = [82, 91, 74, 99, 68]

hot_days = 0
for temp in temperatures:
    if temp < 75:
        continue
    if temp >= 95:
        break
    hot_days += 1

print(hot_days)

Work through the loop by hand:

  • Which values reach hot_days += 1?
  • Which value is skipped by continue?
  • Which value stops the loop with break?
  • What prints at the end?

Use a trace table when if, continue, and break interact.

Chapter 3 Checklist

Skill Check
Trace control flow Can you predict which branch or loop body runs next?
Write branches Can you choose among if, else, elif, and nested if?
Choose loops Can you decide between for and while?
Control loops Can you explain break, continue, and pass?
Accumulate results Can you total, count, or collect values in a loop?

End of Chapter 3

Next: Chapter 4 — Functions

defining functions · parameters · return values · recursion