Control Flow
Loop Patterns
Common Iteration Techniques
A countdown timer needs to go 10, 9, 8... 1, 0. A report processes every 5th record for sampling. A game loop runs until the player quits. Each scenario uses a different loop pattern.
Count up (1 to 10)
The most basic loop pattern - counting from start to end.
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
start =
end =
print(f"Counting from {start} to {end}:")
for i in range(start, end + 1):
print(i)
# Practical: sum numbers in range
total = sum(range(1, 101))
print(f"Sum of 1-100: {total}")
# Or with a loop
total = 0
for i in range(1, 101):
total += i
print(f"Sum (loop): {total}")
Python's range() makes counting loops clean and readable.
Count down (countdown timer)
Looping in reverse order - start high, go low.
start =
print(f"Countdown from {start}:")
for i in range(start, 0, -1):
print(i)
print("Liftoff!")
# Practical: reverse list traversal
arr = [10, 20, 30, 40, 50]
print("\nArray in reverse:")
for i in range(len(arr) - 1, -1, -1):
print(f"Index {i}: {arr[i]}")
# Pythonic way: reversed()
print("\nUsing reversed():")
for item in reversed(arr):
print(item)
# Or slice
print("\nUsing slice:")
for item in arr[::-1]:
print(item)
start =
print(f"Countdown from {start}:")
for i in range(start, 0, -1):
print(i)
print("Liftoff!")
# Practical: reverse list traversal
arr = [10, 20, 30, 40, 50]
print("\nArray in reverse:")
for i in range(len(arr) - 1, -1, -1):
print(f"Index {i}: {arr[i]}")
# Pythonic way: reversed()
print("\nUsing reversed():")
for item in reversed(arr):
print(item)
# Or slice
print("\nUsing slice:")
for item in arr[::-1]:
print(item)
start =
print(f"Countdown from {start}:")
for i in range(start, 0, -1):
print(i)
print("Liftoff!")
# Practical: reverse list traversal
arr = [10, 20, 30, 40, 50]
print("\nArray in reverse:")
for i in range(len(arr) - 1, -1, -1):
print(f"Index {i}: {arr[i]}")
# Pythonic way: reversed()
print("\nUsing reversed():")
for item in reversed(arr):
print(item)
# Or slice
print("\nUsing slice:")
for item in arr[::-1]:
print(item)
range(start, end, step) with negative step counts backwards.
Step by N (every nth element)
Skip elements by using a step value.
step =
# Count by step
print(f"Counting by {step}:")
for i in range(0, 51, step):
print(i)
# Practical: process every other element
names = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]
print("\nEvery other name:")
for i in range(0, len(names), 2):
print(names[i])
# Pythonic: slice with step
print("\nUsing slice:")
for name in names[::2]:
print(name)
# Odd numbers only
print("\nOdd numbers 1-20:")
odds = list(range(1, 21, 2))
print(odds)
step =
# Count by step
print(f"Counting by {step}:")
for i in range(0, 51, step):
print(i)
# Practical: process every other element
names = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]
print("\nEvery other name:")
for i in range(0, len(names), 2):
print(names[i])
# Pythonic: slice with step
print("\nUsing slice:")
for name in names[::2]:
print(name)
# Odd numbers only
print("\nOdd numbers 1-20:")
odds = list(range(1, 21, 2))
print(odds)
step =
# Count by step
print(f"Counting by {step}:")
for i in range(0, 51, step):
print(i)
# Practical: process every other element
names = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]
print("\nEvery other name:")
for i in range(0, len(names), 2):
print(names[i])
# Pythonic: slice with step
print("\nUsing slice:")
for name in names[::2]:
print(name)
# Odd numbers only
print("\nOdd numbers 1-20:")
odds = list(range(1, 21, 2))
print(odds)
The third argument to range() is the step size.
While with condition
Loop until some condition becomes false.
# Guessing game simulation
secret =
guess = 1
attempts = 0
while guess != secret:
print(f"Trying {guess}... wrong!")
guess += 1
attempts += 1
print(f"Found {secret} in {attempts} attempts!")
# Practical: process until sentinel value
data = [10, 20, 30, -1, 40, 50] # -1 is sentinel
i = 0
total = 0
print("\nSum until -1:")
while i < len(data) and data[i] != -1:
total += data[i]
i += 1
print(f"Sum: {total}")
# Pythonic: itertools.takewhile
from itertools import takewhile
data2 = [10, 20, 30, -1, 40, 50]
total2 = sum(takewhile(lambda x: x != -1, data2))
print(f"Sum (takewhile): {total2}")
# Guessing game simulation
secret =
guess = 1
attempts = 0
while guess != secret:
print(f"Trying {guess}... wrong!")
guess += 1
attempts += 1
print(f"Found {secret} in {attempts} attempts!")
# Practical: process until sentinel value
data = [10, 20, 30, -1, 40, 50] # -1 is sentinel
i = 0
total = 0
print("\nSum until -1:")
while i < len(data) and data[i] != -1:
total += data[i]
i += 1
print(f"Sum: {total}")
# Pythonic: itertools.takewhile
from itertools import takewhile
data2 = [10, 20, 30, -1, 40, 50]
total2 = sum(takewhile(lambda x: x != -1, data2))
print(f"Sum (takewhile): {total2}")
# Guessing game simulation
secret =
guess = 1
attempts = 0
while guess != secret:
print(f"Trying {guess}... wrong!")
guess += 1
attempts += 1
print(f"Found {secret} in {attempts} attempts!")
# Practical: process until sentinel value
data = [10, 20, 30, -1, 40, 50] # -1 is sentinel
i = 0
total = 0
print("\nSum until -1:")
while i < len(data) and data[i] != -1:
total += data[i]
i += 1
print(f"Sum: {total}")
# Pythonic: itertools.takewhile
from itertools import takewhile
data2 = [10, 20, 30, -1, 40, 50]
total2 = sum(takewhile(lambda x: x != -1, data2))
print(f"Sum (takewhile): {total2}")
Use while when you don't know how many iterations ahead of time.
Emulating do-while
Python doesn't have do-while, but you can emulate it.
# Python doesn't have do-while, but here are alternatives:
# Pattern 1: while True with break at end
print("=== Pattern 1: while True + break ===")
choice = 0
while True:
print("=== Menu ===")
print("1. Play")
print("2. Settings")
print("3. Exit")
print(f"Choice: {choice}")
# Simulate getting input
choice = 3
if choice == 3:
break
print("Goodbye!")
# Pattern 2: Loop-and-a-half
print("\n=== Pattern 2: Loop-and-a-half ===")
attempts = 0
while True:
attempts += 1
print(f"Attempt {attempts}")
# Simulate: succeed on 3rd try
success = (attempts == 3)
if success:
print("Success!")
break
print("Retrying...")
# Pattern 3: Assignment expression (walrus operator)
print("\n=== Pattern 3: Walrus operator ===")
numbers = iter([1, 2, 3, 0, 4, 5])
while (n := next(numbers, None)) is not None and n != 0:
print(f"Processing: {n}")
print("Stopped at 0 or end")
Use while True with break at the end, or loop-and-a-half pattern.
Exercise: infinite_patterns.py
Explore intentional infinite loops and how to use them safely