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 = 1
end = 10
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 = 0
end = 10
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 = 5
end = 10
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 = 1
end = 5
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 = 1
end = 20
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 ← 1, end ← 10
1start→ 1 = 1 #@start=5, 02end→ 10 = 10 #@end=5, 2034print(f"Counting from {start1} to {end10}:")5for i in range(start, end + 1): #?range_inclusiveoutputCounting from 1 to 10:for i in range(start, end + 1): #?range_inclusive
pass 1 of 104print(f"Counting from {start} to {end}:")5for i1 in range(start1, end10 + 1): #?range_inclusive6 print(i1)output1All 10 passes — pass 1 is the card above pass i1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 total ← 5050
8# Practical: sum numbers in range9total→ 5050 = sum(range(1, 101))10print(f"Sum of 1-100: {total5050}")1112# Or with a loop13total→ 0 = 014for i in range(1, 101):outputSum of 1-100: 5050total ← 1
pass 1 of 10013total = 014for i1 in range(1, 101):15 total→ 1 += i116print(f"Sum (loop): {total}")100 passes — pass 1 is the card above pass itotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 7 7 21 → 28 8 8 28 → 36 9 9 36 → 45 ⋯ 89 more passes ⋯ 99 99 4851 → 4950 100 100 4950 → 5050 print(f"Sum (loop): {total}")
15 total += i16print(f"Sum (loop): {total5050}")outputSum (loop): 5050
start ← 0, end ← 10
1start→ 0 = 02end→ 10 = 1034print(f"Counting from {start0} to {end10}:")5for i in range(start, end + 1):outputCounting from 0 to 10:for i in range(start, end + 1):
pass 1 of 114print(f"Counting from {start} to {end}:")5for i0 in range(start0, end10 + 1):6 print(i0)output0All 11 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 9 11 10 total ← 5050
8# Practical: sum numbers in range9total→ 5050 = sum(range(1, 101))10print(f"Sum of 1-100: {total5050}")1112# Or with a loop13total→ 0 = 014for i in range(1, 101):outputSum of 1-100: 5050total ← 1
pass 1 of 10013total = 014for i1 in range(1, 101):15 total→ 1 += i116print(f"Sum (loop): {total}")100 passes — pass 1 is the card above pass itotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 7 7 21 → 28 8 8 28 → 36 9 9 36 → 45 ⋯ 89 more passes ⋯ 99 99 4851 → 4950 100 100 4950 → 5050 print(f"Sum (loop): {total}")
15 total += i16print(f"Sum (loop): {total5050}")outputSum (loop): 5050
start ← 5, end ← 10
1start→ 5 = 52end→ 10 = 1034print(f"Counting from {start5} to {end10}:")5for i in range(start, end + 1):outputCounting from 5 to 10:for i in range(start, end + 1):
pass 1 of 64print(f"Counting from {start} to {end}:")5for i5 in range(start5, end10 + 1):6 print(i5)output5All 6 passes — pass 1 is the card above pass i1 5 2 6 3 7 4 8 5 9 6 10 total ← 5050
8# Practical: sum numbers in range9total→ 5050 = sum(range(1, 101))10print(f"Sum of 1-100: {total5050}")1112# Or with a loop13total→ 0 = 014for i in range(1, 101):outputSum of 1-100: 5050total ← 1
pass 1 of 10013total = 014for i1 in range(1, 101):15 total→ 1 += i116print(f"Sum (loop): {total}")100 passes — pass 1 is the card above pass itotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 7 7 21 → 28 8 8 28 → 36 9 9 36 → 45 ⋯ 89 more passes ⋯ 99 99 4851 → 4950 100 100 4950 → 5050 print(f"Sum (loop): {total}")
15 total += i16print(f"Sum (loop): {total5050}")outputSum (loop): 5050
start ← 1, end ← 5
1start→ 1 = 12end→ 5 = 534print(f"Counting from {start1} to {end5}:")5for i in range(start, end + 1):outputCounting from 1 to 5:for i in range(start, end + 1):
pass 1 of 54print(f"Counting from {start} to {end}:")5for i1 in range(start1, end5 + 1):6 print(i1)output1All 5 passes — pass 1 is the card above pass i1 1 2 2 3 3 4 4 5 5 total ← 5050
8# Practical: sum numbers in range9total→ 5050 = sum(range(1, 101))10print(f"Sum of 1-100: {total5050}")1112# Or with a loop13total→ 0 = 014for i in range(1, 101):outputSum of 1-100: 5050total ← 1
pass 1 of 10013total = 014for i1 in range(1, 101):15 total→ 1 += i116print(f"Sum (loop): {total}")100 passes — pass 1 is the card above pass itotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 7 7 21 → 28 8 8 28 → 36 9 9 36 → 45 ⋯ 89 more passes ⋯ 99 99 4851 → 4950 100 100 4950 → 5050 print(f"Sum (loop): {total}")
15 total += i16print(f"Sum (loop): {total5050}")outputSum (loop): 5050
start ← 1, end ← 20
1start→ 1 = 12end→ 20 = 2034print(f"Counting from {start1} to {end20}:")5for i in range(start, end + 1):outputCounting from 1 to 20:for i in range(start, end + 1):
pass 1 of 204print(f"Counting from {start} to {end}:")5for i1 in range(start1, end20 + 1):6 print(i1)output120 passes — pass 1 is the card above pass i1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 ⋯ 9 more passes ⋯ 19 19 20 20 total ← 5050
8# Practical: sum numbers in range9total→ 5050 = sum(range(1, 101))10print(f"Sum of 1-100: {total5050}")1112# Or with a loop13total→ 0 = 014for i in range(1, 101):outputSum of 1-100: 5050total ← 1
pass 1 of 10013total = 014for i1 in range(1, 101):15 total→ 1 += i116print(f"Sum (loop): {total}")100 passes — pass 1 is the card above pass itotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 7 7 21 → 28 8 8 28 → 36 9 9 36 → 45 ⋯ 89 more passes ⋯ 99 99 4851 → 4950 100 100 4950 → 5050 print(f"Sum (loop): {total}")
15 total += i16print(f"Sum (loop): {total5050}")outputSum (loop): 5050
Python's range() makes counting loops clean and readable.
Count down (countdown timer)
Looping in reverse order - start high, go low.
start = 10
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 = 3
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 = 5
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 ← 10
1start→ 10 = 10 #@start=5, 323print(f"Countdown from {start10}:")4for i in range(start, 0, -1): #?negative_stepoutputCountdown from 10:for i in range(start, 0, -1): #?negative_step
pass 1 of 103print(f"Countdown from {start}:")4for i10 in range(start10, 0, -1): #?negative_step5 print(i10)6print("Liftoff!")output10All 10 passes — pass 1 is the card above pass i1 10 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 10 1 arr ← [10, 20, 30, 40, 50]
5 print(i)6print("Liftoff!")78# Practical: reverse list traversal9arr→ [10, 20, 30, 40, 50] = [10, 20, 30, 40, 50]10print("\nArray in reverse:")11for i in range(len(arr) - 1, -1, -1):outputLiftoff! Array in reverse:for i in range(len(arr) - 1, -1, -1):
pass 1 of 510print("\nArray in reverse:")11for i4 in range(len(arr[10, 20, 30, 40, 50]) - 1, -1, -1):12 print(f"Index {i4}: {arr[i]50}")outputIndex 4: 50All 5 passes — pass 1 is the card above pass iarr[i]1 4 50 2 3 40 3 2 30 4 1 20 5 0 10 print(" Using reversed():")
14# Pythonic way: reversed()15print("\nUsing reversed():")16for item in reversed(arr):output Using reversed():for item in reversed(arr):
pass 1 of 515print("\nUsing reversed():")16for item50 in reversed(arr[10, 20, 30, 40, 50]):17 print(item50)output50All 5 passes — pass 1 is the card above pass item1 50 2 40 3 30 4 20 5 10 print(" Using slice:")
19# Or slice20print("\nUsing slice:")21for item in arr[::-1]:output Using slice:for item in arr[::-1]:
pass 1 of 520print("\nUsing slice:")21for item50 in arr[::-1][50, 40, 30, 20, 10]:22 print(item50)output50All 5 passes — pass 1 is the card above pass item1 50 2 40 3 30 4 20 5 10
start ← 3
1start→ 3 = 323print(f"Countdown from {start3}:")4for i in range(start, 0, -1):outputCountdown from 3:for i in range(start, 0, -1):
pass 1 of 33print(f"Countdown from {start}:")4for i3 in range(start3, 0, -1):5 print(i3)6print("Liftoff!")output3All 3 passes — pass 1 is the card above pass i1 3 2 2 3 1 arr ← [10, 20, 30, 40, 50]
5 print(i)6print("Liftoff!")78# Practical: reverse list traversal9arr→ [10, 20, 30, 40, 50] = [10, 20, 30, 40, 50]10print("\nArray in reverse:")11for i in range(len(arr) - 1, -1, -1):outputLiftoff! Array in reverse:for i in range(len(arr) - 1, -1, -1):
pass 1 of 510print("\nArray in reverse:")11for i4 in range(len(arr[10, 20, 30, 40, 50]) - 1, -1, -1):12 print(f"Index {i4}: {arr[i]50}")outputIndex 4: 50All 5 passes — pass 1 is the card above pass iarr[i]1 4 50 2 3 40 3 2 30 4 1 20 5 0 10 print(" Using reversed():")
14# Pythonic way: reversed()15print("\nUsing reversed():")16for item in reversed(arr):output Using reversed():for item in reversed(arr):
pass 1 of 515print("\nUsing reversed():")16for item50 in reversed(arr[10, 20, 30, 40, 50]):17 print(item50)output50All 5 passes — pass 1 is the card above pass item1 50 2 40 3 30 4 20 5 10 print(" Using slice:")
19# Or slice20print("\nUsing slice:")21for item in arr[::-1]:output Using slice:for item in arr[::-1]:
pass 1 of 520print("\nUsing slice:")21for item50 in arr[::-1][50, 40, 30, 20, 10]:22 print(item50)output50All 5 passes — pass 1 is the card above pass item1 50 2 40 3 30 4 20 5 10
start ← 5
1start→ 5 = 523print(f"Countdown from {start5}:")4for i in range(start, 0, -1):outputCountdown from 5:for i in range(start, 0, -1):
pass 1 of 53print(f"Countdown from {start}:")4for i5 in range(start5, 0, -1):5 print(i5)6print("Liftoff!")output5All 5 passes — pass 1 is the card above pass i1 5 2 4 3 3 4 2 5 1 arr ← [10, 20, 30, 40, 50]
5 print(i)6print("Liftoff!")78# Practical: reverse list traversal9arr→ [10, 20, 30, 40, 50] = [10, 20, 30, 40, 50]10print("\nArray in reverse:")11for i in range(len(arr) - 1, -1, -1):outputLiftoff! Array in reverse:for i in range(len(arr) - 1, -1, -1):
pass 1 of 510print("\nArray in reverse:")11for i4 in range(len(arr[10, 20, 30, 40, 50]) - 1, -1, -1):12 print(f"Index {i4}: {arr[i]50}")outputIndex 4: 50All 5 passes — pass 1 is the card above pass iarr[i]1 4 50 2 3 40 3 2 30 4 1 20 5 0 10 print(" Using reversed():")
14# Pythonic way: reversed()15print("\nUsing reversed():")16for item in reversed(arr):output Using reversed():for item in reversed(arr):
pass 1 of 515print("\nUsing reversed():")16for item50 in reversed(arr[10, 20, 30, 40, 50]):17 print(item50)output50All 5 passes — pass 1 is the card above pass item1 50 2 40 3 30 4 20 5 10 print(" Using slice:")
19# Or slice20print("\nUsing slice:")21for item in arr[::-1]:output Using slice:for item in arr[::-1]:
pass 1 of 520print("\nUsing slice:")21for item50 in arr[::-1][50, 40, 30, 20, 10]:22 print(item50)output50All 5 passes — pass 1 is the card above pass item1 50 2 40 3 30 4 20 5 10
range(start, end, step) with negative step counts backwards.
Step by N (every nth element)
Skip elements by using a step value.
step = 5
# 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 = 2
# 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 = 10
# 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 ← 5
1step→ 5 = 5 #@step=2, 1023# Count by step4print(f"Counting by {step5}:")5for i in range(0, 51, step):outputCounting by 5:for i in range(0, 51, step):
pass 1 of 114print(f"Counting by {step}:")5for i0 in range(0, 51, step5):6 print(i0)output0All 11 passes — pass 1 is the card above pass i1 0 2 5 3 10 4 15 5 20 6 25 7 30 8 35 9 40 10 45 11 50 names ← ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']
8# Practical: process every other element9names→ ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'] = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]10print("\nEvery other name:")11for i in range(0, len(names), 2):output Every other name:for i in range(0, len(names), 2):
pass 1 of 310print("\nEvery other name:")11for i0 in range(0, len(names['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']), 2):12 print(names[i]Alice)outputAliceAll 3 passes — pass 1 is the card above pass inames[i]1 0 Alice 2 2 Charlie 3 4 Eve print(" Using slice:")
14# Pythonic: slice with step15print("\nUsing slice:")16for name in names[::2]:output Using slice:for name in names[::2]:
pass 1 of 315print("\nUsing slice:")16for nameAlice in names[::2]['Alice', 'Charlie', 'Eve']:17 print(nameAlice)outputAliceAll 3 passes — pass 1 is the card above pass name1 Alice 2 Charlie 3 Eve odds ← [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
19# Odd numbers only20print("\nOdd numbers 1-20:")21odds→ [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] = list(range(1, 21, 2))22print(odds[1, 3, 5, 7, 9, 11, 13, 15, 17, 19])output Odd numbers 1-20: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
step ← 2
1step→ 2 = 223# Count by step4print(f"Counting by {step2}:")5for i in range(0, 51, step):outputCounting by 2:for i in range(0, 51, step):
pass 1 of 264print(f"Counting by {step}:")5for i0 in range(0, 51, step2):6 print(i0)output026 passes — pass 1 is the card above pass i1 0 2 2 3 4 4 6 5 8 6 10 7 12 8 14 9 16 ⋯ 15 more passes ⋯ 25 48 26 50 names ← ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']
8# Practical: process every other element9names→ ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'] = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]10print("\nEvery other name:")11for i in range(0, len(names), 2):output Every other name:for i in range(0, len(names), 2):
pass 1 of 310print("\nEvery other name:")11for i0 in range(0, len(names['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']), 2):12 print(names[i]Alice)outputAliceAll 3 passes — pass 1 is the card above pass inames[i]1 0 Alice 2 2 Charlie 3 4 Eve print(" Using slice:")
14# Pythonic: slice with step15print("\nUsing slice:")16for name in names[::2]:output Using slice:for name in names[::2]:
pass 1 of 315print("\nUsing slice:")16for nameAlice in names[::2]['Alice', 'Charlie', 'Eve']:17 print(nameAlice)outputAliceAll 3 passes — pass 1 is the card above pass name1 Alice 2 Charlie 3 Eve odds ← [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
19# Odd numbers only20print("\nOdd numbers 1-20:")21odds→ [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] = list(range(1, 21, 2))22print(odds[1, 3, 5, 7, 9, 11, 13, 15, 17, 19])output Odd numbers 1-20: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
step ← 10
1step→ 10 = 1023# Count by step4print(f"Counting by {step10}:")5for i in range(0, 51, step):outputCounting by 10:for i in range(0, 51, step):
pass 1 of 64print(f"Counting by {step}:")5for i0 in range(0, 51, step10):6 print(i0)output0All 6 passes — pass 1 is the card above pass i1 0 2 10 3 20 4 30 5 40 6 50 names ← ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']
8# Practical: process every other element9names→ ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'] = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]10print("\nEvery other name:")11for i in range(0, len(names), 2):output Every other name:for i in range(0, len(names), 2):
pass 1 of 310print("\nEvery other name:")11for i0 in range(0, len(names['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']), 2):12 print(names[i]Alice)outputAliceAll 3 passes — pass 1 is the card above pass inames[i]1 0 Alice 2 2 Charlie 3 4 Eve print(" Using slice:")
14# Pythonic: slice with step15print("\nUsing slice:")16for name in names[::2]:output Using slice:for name in names[::2]:
pass 1 of 315print("\nUsing slice:")16for nameAlice in names[::2]['Alice', 'Charlie', 'Eve']:17 print(nameAlice)outputAliceAll 3 passes — pass 1 is the card above pass name1 Alice 2 Charlie 3 Eve odds ← [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
19# Odd numbers only20print("\nOdd numbers 1-20:")21odds→ [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] = list(range(1, 21, 2))22print(odds[1, 3, 5, 7, 9, 11, 13, 15, 17, 19])output Odd numbers 1-20: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
The third argument to range() is the step size.
While with condition
Loop until some condition becomes false.
# Guessing game simulation
secret = 7
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 = 3
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 = 9
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}")
secret ← 7, guess ← 1, attempts ← 0
1# Guessing game simulation2secret→ 7 = 7 #@secret=3, 93guess→ 1 = 14attempts→ 0 = 0guess ← 2, attempts ← 1
pass 1 of 66while guess1 != secret7: #?while_condition7 print(f"Trying {guess1}... wrong!")8 guess→ 2 += 19 attempts→ 1 += 1outputTrying 1... wrong!All 6 passes — pass 1 is the card above pass guessattempts1 1 → 2 0 → 1 2 2 → 3 1 → 2 3 3 → 4 2 → 3 4 4 → 5 3 → 4 5 5 → 6 4 → 5 6 6 → 7 5 → 6 data ← [10, 20, 30, -1, 40, 50], i ← 0, total ← 0
11print(f"Found {secret7} in {attempts6} attempts!")1213# Practical: process until sentinel value14data→ [10, 20, 30, -1, 40, 50] = [10, 20, 30, -1, 40, 50] # -1 is sentinel15i→ 0 = 016total→ 0 = 01718print("\nSum until -1:")19while i < len(data) and data[i] != -1:outputFound 7 in 6 attempts! Sum until -1:total ← 10, i ← 1
pass 1 of 318print("\nSum until -1:")19while i0 < len(data[10, 20, 30, -1, 40, 50]) and data[i]10 != -1:20 total→ 10 += data[i]1021 i→ 1 += 1All 3 passes — pass 1 is the card above pass data[i]totali1 10 0 → 10 0 → 1 2 20 10 → 30 1 → 2 3 30 30 → 60 2 → 3 data2 ← [10, 20, 30, -1, 40, 50], total2 ← 60
23print(f"Sum: {total60}")2425# Pythonic: itertools.takewhile26from itertools import takewhile27data2→ [10, 20, 30, -1, 40, 50] = [10, 20, 30, -1, 40, 50]28total2→ 60 = sum(takewhile(lambda x: x != -1, data2[10, 20, 30, -1, 40, 50]))29print(f"Sum (takewhile): {total260}")outputSum: 60 Sum (takewhile): 60
secret ← 3, guess ← 1, attempts ← 0
1# Guessing game simulation2secret→ 3 = 33guess→ 1 = 14attempts→ 0 = 0guess ← 2, attempts ← 1
pass 1 of 26while guess1 != secret3:7 print(f"Trying {guess1}... wrong!")8 guess→ 2 += 19 attempts→ 1 += 1outputTrying 1... wrong!guess ← 3, attempts ← 2
pass 2 of 26while guess2 != secret3:7 print(f"Trying {guess2}... wrong!")8 guess→ 3 += 19 attempts→ 2 += 1outputTrying 2... wrong!data ← [10, 20, 30, -1, 40, 50], i ← 0, total ← 0
11print(f"Found {secret3} in {attempts2} attempts!")1213# Practical: process until sentinel value14data→ [10, 20, 30, -1, 40, 50] = [10, 20, 30, -1, 40, 50] # -1 is sentinel15i→ 0 = 016total→ 0 = 01718print("\nSum until -1:")19while i < len(data) and data[i] != -1:outputFound 3 in 2 attempts! Sum until -1:total ← 10, i ← 1
pass 1 of 318print("\nSum until -1:")19while i0 < len(data[10, 20, 30, -1, 40, 50]) and data[i]10 != -1:20 total→ 10 += data[i]1021 i→ 1 += 1All 3 passes — pass 1 is the card above pass data[i]totali1 10 0 → 10 0 → 1 2 20 10 → 30 1 → 2 3 30 30 → 60 2 → 3 data2 ← [10, 20, 30, -1, 40, 50], total2 ← 60
23print(f"Sum: {total60}")2425# Pythonic: itertools.takewhile26from itertools import takewhile27data2→ [10, 20, 30, -1, 40, 50] = [10, 20, 30, -1, 40, 50]28total2→ 60 = sum(takewhile(lambda x: x != -1, data2[10, 20, 30, -1, 40, 50]))29print(f"Sum (takewhile): {total260}")outputSum: 60 Sum (takewhile): 60
secret ← 9, guess ← 1, attempts ← 0
1# Guessing game simulation2secret→ 9 = 93guess→ 1 = 14attempts→ 0 = 0guess ← 2, attempts ← 1
pass 1 of 86while guess1 != secret9:7 print(f"Trying {guess1}... wrong!")8 guess→ 2 += 19 attempts→ 1 += 1outputTrying 1... wrong!All 8 passes — pass 1 is the card above pass guessattempts1 1 → 2 0 → 1 2 2 → 3 1 → 2 3 3 → 4 2 → 3 4 4 → 5 3 → 4 5 5 → 6 4 → 5 6 6 → 7 5 → 6 7 7 → 8 6 → 7 8 8 → 9 7 → 8 data ← [10, 20, 30, -1, 40, 50], i ← 0, total ← 0
11print(f"Found {secret9} in {attempts8} attempts!")1213# Practical: process until sentinel value14data→ [10, 20, 30, -1, 40, 50] = [10, 20, 30, -1, 40, 50] # -1 is sentinel15i→ 0 = 016total→ 0 = 01718print("\nSum until -1:")19while i < len(data) and data[i] != -1:outputFound 9 in 8 attempts! Sum until -1:total ← 10, i ← 1
pass 1 of 318print("\nSum until -1:")19while i0 < len(data[10, 20, 30, -1, 40, 50]) and data[i]10 != -1:20 total→ 10 += data[i]1021 i→ 1 += 1All 3 passes — pass 1 is the card above pass data[i]totali1 10 0 → 10 0 → 1 2 20 10 → 30 1 → 2 3 30 30 → 60 2 → 3 data2 ← [10, 20, 30, -1, 40, 50], total2 ← 60
23print(f"Sum: {total60}")2425# Pythonic: itertools.takewhile26from itertools import takewhile27data2→ [10, 20, 30, -1, 40, 50] = [10, 20, 30, -1, 40, 50]28total2→ 60 = sum(takewhile(lambda x: x != -1, data2[10, 20, 30, -1, 40, 50]))29print(f"Sum (takewhile): {total260}")outputSum: 60 Sum (takewhile): 60
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")
choice ← 0
3# Pattern 1: while True with break at end4print("=== Pattern 1: while True + break ===")5choice→ 0 = 0output=== Pattern 1: while True + break ===choice ← 3
7while True:8 print("=== Menu ===")9 print("1. Play")10 print("2. Settings")11 print("3. Exit")12 print(f"Choice: {choice0}")13 14 # Simulate getting input15 choice→ 3 = 3 #?simulate_inputoutput=== Menu === 1. Play 2. Settings 3. Exit Choice: 0if choice == 3:
17if choice3 == 3:18 breakattempts ← 0
20print("Goodbye!")2122# Pattern 2: Loop-and-a-half23print("\n=== Pattern 2: Loop-and-a-half ===")24attempts→ 0 = 0outputGoodbye! === Pattern 2: Loop-and-a-half ===attempts ← 1, success ← False
pass 1 of 326while True:27 attempts→ 1 += 128 print(f"Attempt {attempts1}")29 30 # Simulate: succeed on 3rd try31 success→ False = (attempts1 == 3)32 33 if success:34 print("Success!")35 break36 37 print("Retrying...")outputAttempt 1 Retrying...All 3 passes — pass 1 is the card above pass attemptssuccess1 0 → 1 False 2 1 → 2 False 3 2 → 3 True if success:
33if successTrue:34 print("Success!")35 breakoutputSuccess!numbers ← ⟨list_iterator A⟩
39# Pattern 3: Assignment expression (walrus operator)40print("\n=== Pattern 3: Walrus operator ===")41numbers→ ⟨list_iterator A⟩ = iter([1, 2, 3, 0, 4, 5])output === Pattern 3: Walrus operator ===while (n := next(numbers, None)) is not None and n != 0:
pass 1 of 343while (n1 := next(numbers⟨list_iterator A⟩, None)) is not None and n != 0:44 print(f"Processing: {n1}")outputProcessing: 1All 3 passes — pass 1 is the card above pass n1 1 2 2 3 3 print("Stopped at 0 or end")
46print("Stopped at 0 or end")outputStopped 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