Python Control Flow

Python's control flow includes if/elif/else, for loops, while loops, and the powerful match statement (Python 3.10+).

if/elif/else

Python
score = 85

if score >= 90:
    grade = "A"
    message = "Excellent!"
elif score >= 80:
    grade = "B"
    message = "Great job!"
elif score >= 70:
    grade = "C"
    message = "Good work!"
elif score >= 60:
    grade = "D"
    message = "Keep trying!"
else:
    grade = "F"
    message = "Study harder!"

print(f"Grade: {grade} — {message}")

# Ternary operator (one-line if/else)
age = 20
status = "adult" if age >= 18 else "minor"

# Nested ternary
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"

for Loops

Python
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# With index (enumerate)
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

# Range function
for i in range(5):          # 0, 1, 2, 3, 4
    print(i)

for i in range(2, 10, 2):   # 2, 4, 6, 8 (start, stop, step)
    print(i)

for i in range(10, 0, -1):  # 10, 9, 8, ..., 1 (countdown)
    print(i)

# Iterating over a dictionary
person = {"name": "Alice", "age": 28, "city": "NYC"}
for key, value in person.items():
    print(f"{key}: {value}")

# Iterating over a string
for char in "Python":
    print(char, end=" ")
# P y t h o n

# Loop with else (runs if loop completes without break)
for n in range(2, 10):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            break
    else:  # This else belongs to the for loop
        print(f"{n} is prime")

while Loops

Python
# Basic while loop
count = 0
while count < 5:
    print(count)
    count += 1

# User input loop
while True:
    command = input("Enter command (quit to exit): ")
    if command == "quit":
        break
    print(f"Executing: {command}")

# While with else
n = 5
while n > 0:
    n -= 1
else:
    print("Countdown complete!")

Loop Control

Python
# break — exit the loop immediately
for i in range(100):
    if i == 5:
        break  # Stop at 5
    print(i)

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

# pass — do nothing (placeholder)
for i in range(10):
    if i % 2 == 0:
        pass  # TODO: handle even numbers later
    print(i)

match Statement (Python 3.10+)

Python
# Pattern matching (like switch/case but much more powerful)
command = "open"

match command:
    case "open":
        print("Opening...")
    case "close":
        print("Closing...")
    case "save":
        print("Saving...")
    case _:
        print("Unknown command")

# Pattern matching with conditions
score = 85
match score:
    case s if s >= 90:
        print("A")
    case s if s >= 80:
        print("B")
    case s if s >= 70:
        print("C")
    case _:
        print("F")

# Pattern matching with data structures
data = {"type": "user", "name": "Alice"}
match data:
    case {"type": "user", "name": str(name)}:
        print(f"Hello, {name}!")
    case {"type": "admin"}:
        print("Admin panel")
    case _:
        print("Unknown data")

Knowledge Check

4 questions — test your understanding

1

What does enumerate(['a', 'b', 'c']) return?

2

What does range(0, 10, 2) produce?

3

What is the purpose of the `else` clause after a `for` loop?

4

What does `match _:` do in a match statement?

Next: Functions