Chapter 3

Control Flow

3.0 Intro · 3.1 Conditionals · 3.2 Iteration

← → or Space to navigate · F for fullscreen

3.1 Conditionals

if / elif / else · nested conditionals · conditional expressions

if / elif / else

score = 85

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

print(f"Grade: {grade}")   # Grade: B
  • Conditions are evaluated top-to-bottom.
  • Only the first matching branch runs.
  • else is optional; catches everything remaining.
  • Any expression that is truthy/falsy works as a condition.

0, "", [], None are falsy. Everything else is truthy — no need for == True.

Nested Conditionals & Logical Operators

Nested (avoid when possible)

if x > 0:
    if x < 10:
        print("single digit")

Better: logical operators

if 0 < x < 10:       # chained comparison
    print("single digit")

if x > 0 and x < 10: # equivalent
    print("single digit")

Common patterns

# Guard clause — exit early
def process(data):
    if not data:
        return []
    # ... rest of function

# Membership test
if color in {"red", "green", "blue"}:
    print("primary")

Conditional Expressions (Ternary)

A concise one-liner for choosing between two values.

# if/else block
if x > 0:
    label = "positive"
else:
    label = "non-positive"

# Equivalent conditional expression
label = "positive" if x > 0 else "non-positive"

Read as: "give me A if condition is true, else B." Use when both branches are simple expressions.

3.2 Iteration

for loops · while loops · break / continue · accumulator pattern

for Loops

# Iterate over a sequence
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

# Iterate with index
for i, fruit in enumerate(["apple", "banana"]):
    print(i, fruit)

# Range
for n in range(1, 6):
    print(n)   # 1 2 3 4 5
# Iterate over dict
scores = {"alice": 92, "bob": 85}
for name, score in scores.items():
    print(f"{name}: {score}")

# List comprehension (Pythonic)
squares = [x**2 for x in range(10)]
evens   = [x for x in range(20) if x % 2 == 0]

while Loops & Loop Control

# while loop
n = 1
while n < 100:
    n *= 2
print(n)   # 128

# break — exit the loop early
for i in range(10):
    if i == 5:
        break
    print(i)   # 0 1 2 3 4

# continue — skip to next iteration
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)   # 1 3 5 7 9

Accumulator pattern

# Sum (accumulate a number)
total = 0
for score in scores:
    total += score

# Collect (accumulate a list)
passing = []
for score in scores:
    if score >= 60:
        passing.append(score)

# Count (accumulate a tally)
count = 0
for score in scores:
    if score >= 90:
        count += 1

Chapter 3 — Quick Reference

Concept Key syntax / notes
if / elif / else First matching branch wins
Chained comparison 0 < x < 10
Conditional expression A if condition else B
for loop for item in iterable:
range range(start, stop, step)
enumerate for i, v in enumerate(seq):
while loop Runs while condition is truthy
break / continue Exit loop / skip to next iteration
Accumulator Initialize before loop; update inside

End of Chapter 3

Next: Chapter 4 — Functions

defining functions · parameters · return values · recursion