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.

example
count_up.py
Replay: real traced execution (multi-file project)
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}")

  1. 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_inclusive
    outputCounting from 1 to 10:
  2. for i in range(start, end + 1): #?range_inclusive

    pass 1 of 10
    4print(f"Counting from {start} to {end}:")5for i1 in range(start1, end10 + 1):  #?range_inclusive6    print(i1)
    output1
    All 10 passes — pass 1 is the card above
    passi
    11
    22
    33
    44
    55
    66
    77
    88
    99
    1010
  3. 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: 5050
  4. total ← 1

    pass 1 of 100
    13total = 014for i1 in range(1, 101):15    total→ 1 += i116print(f"Sum (loop): {total}")
    100 passes — pass 1 is the card above
    passitotal
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
    7721 28
    8828 36
    9936 45
    ⋯ 89 more passes ⋯
    99994851 4950
    1001004950 5050
  5. print(f"Sum (loop): {total}")

    15    total += i16print(f"Sum (loop): {total5050}")
    outputSum (loop): 5050
  1. 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:
  2. for i in range(start, end + 1):

    pass 1 of 11
    4print(f"Counting from {start} to {end}:")5for i0 in range(start0, end10 + 1):6    print(i0)
    output0
    All 11 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
    98
    109
    1110
  3. 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: 5050
  4. total ← 1

    pass 1 of 100
    13total = 014for i1 in range(1, 101):15    total→ 1 += i116print(f"Sum (loop): {total}")
    100 passes — pass 1 is the card above
    passitotal
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
    7721 28
    8828 36
    9936 45
    ⋯ 89 more passes ⋯
    99994851 4950
    1001004950 5050
  5. print(f"Sum (loop): {total}")

    15    total += i16print(f"Sum (loop): {total5050}")
    outputSum (loop): 5050
  1. 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:
  2. for i in range(start, end + 1):

    pass 1 of 6
    4print(f"Counting from {start} to {end}:")5for i5 in range(start5, end10 + 1):6    print(i5)
    output5
    All 6 passes — pass 1 is the card above
    passi
    15
    26
    37
    48
    59
    610
  3. 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: 5050
  4. total ← 1

    pass 1 of 100
    13total = 014for i1 in range(1, 101):15    total→ 1 += i116print(f"Sum (loop): {total}")
    100 passes — pass 1 is the card above
    passitotal
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
    7721 28
    8828 36
    9936 45
    ⋯ 89 more passes ⋯
    99994851 4950
    1001004950 5050
  5. print(f"Sum (loop): {total}")

    15    total += i16print(f"Sum (loop): {total5050}")
    outputSum (loop): 5050
  1. 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:
  2. for i in range(start, end + 1):

    pass 1 of 5
    4print(f"Counting from {start} to {end}:")5for i1 in range(start1, end5 + 1):6    print(i1)
    output1
    All 5 passes — pass 1 is the card above
    passi
    11
    22
    33
    44
    55
  3. 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: 5050
  4. total ← 1

    pass 1 of 100
    13total = 014for i1 in range(1, 101):15    total→ 1 += i116print(f"Sum (loop): {total}")
    100 passes — pass 1 is the card above
    passitotal
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
    7721 28
    8828 36
    9936 45
    ⋯ 89 more passes ⋯
    99994851 4950
    1001004950 5050
  5. print(f"Sum (loop): {total}")

    15    total += i16print(f"Sum (loop): {total5050}")
    outputSum (loop): 5050
  1. 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:
  2. for i in range(start, end + 1):

    pass 1 of 20
    4print(f"Counting from {start} to {end}:")5for i1 in range(start1, end20 + 1):6    print(i1)
    output1
    20 passes — pass 1 is the card above
    passi
    11
    22
    33
    44
    55
    66
    77
    88
    99
    ⋯ 9 more passes ⋯
    1919
    2020
  3. 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: 5050
  4. total ← 1

    pass 1 of 100
    13total = 014for i1 in range(1, 101):15    total→ 1 += i116print(f"Sum (loop): {total}")
    100 passes — pass 1 is the card above
    passitotal
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
    7721 28
    8828 36
    9936 45
    ⋯ 89 more passes ⋯
    99994851 4950
    1001004950 5050
  5. print(f"Sum (loop): {total}")

    15    total += i16print(f"Sum (loop): {total5050}")
    outputSum (loop): 5050

Python's range() makes counting loops clean and readable.

range `range(stop)`, `range(start, stop)`, `range(start, stop, step)`

Count down (countdown timer)

Looping in reverse order - start high, go low.

start
count_down.py
Replay: real traced execution (multi-file project)
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)

  1. start ← 10

    1start→ 10 = 10  #@start=5, 323print(f"Countdown from {start10}:")4for i in range(start, 0, -1):  #?negative_step
    outputCountdown from 10:
  2. for i in range(start, 0, -1): #?negative_step

    pass 1 of 10
    3print(f"Countdown from {start}:")4for i10 in range(start10, 0, -1):  #?negative_step5    print(i10)6print("Liftoff!")
    output10
    All 10 passes — pass 1 is the card above
    passi
    110
    29
    38
    47
    56
    65
    74
    83
    92
    101
  3. 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:
  4. for i in range(len(arr) - 1, -1, -1):

    pass 1 of 5
    10print("\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: 50
    All 5 passes — pass 1 is the card above
    passiarr[i]
    1450
    2340
    3230
    4120
    5010
  5. print(" Using reversed():")

    14# Pythonic way: reversed()15print("\nUsing reversed():")16for item in reversed(arr):
    output
    Using reversed():
  6. for item in reversed(arr):

    pass 1 of 5
    15print("\nUsing reversed():")16for item50 in reversed(arr[10, 20, 30, 40, 50]):17    print(item50)
    output50
    All 5 passes — pass 1 is the card above
    passitem
    150
    240
    330
    420
    510
  7. print(" Using slice:")

    19# Or slice20print("\nUsing slice:")21for item in arr[::-1]:
    output
    Using slice:
  8. for item in arr[::-1]:

    pass 1 of 5
    20print("\nUsing slice:")21for item50 in arr[::-1][50, 40, 30, 20, 10]:22    print(item50)
    output50
    All 5 passes — pass 1 is the card above
    passitem
    150
    240
    330
    420
    510
  1. start ← 3

    1start→ 3 = 323print(f"Countdown from {start3}:")4for i in range(start, 0, -1):
    outputCountdown from 3:
  2. for i in range(start, 0, -1):

    pass 1 of 3
    3print(f"Countdown from {start}:")4for i3 in range(start3, 0, -1):5    print(i3)6print("Liftoff!")
    output3
    All 3 passes — pass 1 is the card above
    passi
    13
    22
    31
  3. 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:
  4. for i in range(len(arr) - 1, -1, -1):

    pass 1 of 5
    10print("\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: 50
    All 5 passes — pass 1 is the card above
    passiarr[i]
    1450
    2340
    3230
    4120
    5010
  5. print(" Using reversed():")

    14# Pythonic way: reversed()15print("\nUsing reversed():")16for item in reversed(arr):
    output
    Using reversed():
  6. for item in reversed(arr):

    pass 1 of 5
    15print("\nUsing reversed():")16for item50 in reversed(arr[10, 20, 30, 40, 50]):17    print(item50)
    output50
    All 5 passes — pass 1 is the card above
    passitem
    150
    240
    330
    420
    510
  7. print(" Using slice:")

    19# Or slice20print("\nUsing slice:")21for item in arr[::-1]:
    output
    Using slice:
  8. for item in arr[::-1]:

    pass 1 of 5
    20print("\nUsing slice:")21for item50 in arr[::-1][50, 40, 30, 20, 10]:22    print(item50)
    output50
    All 5 passes — pass 1 is the card above
    passitem
    150
    240
    330
    420
    510
  1. start ← 5

    1start→ 5 = 523print(f"Countdown from {start5}:")4for i in range(start, 0, -1):
    outputCountdown from 5:
  2. for i in range(start, 0, -1):

    pass 1 of 5
    3print(f"Countdown from {start}:")4for i5 in range(start5, 0, -1):5    print(i5)6print("Liftoff!")
    output5
    All 5 passes — pass 1 is the card above
    passi
    15
    24
    33
    42
    51
  3. 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:
  4. for i in range(len(arr) - 1, -1, -1):

    pass 1 of 5
    10print("\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: 50
    All 5 passes — pass 1 is the card above
    passiarr[i]
    1450
    2340
    3230
    4120
    5010
  5. print(" Using reversed():")

    14# Pythonic way: reversed()15print("\nUsing reversed():")16for item in reversed(arr):
    output
    Using reversed():
  6. for item in reversed(arr):

    pass 1 of 5
    15print("\nUsing reversed():")16for item50 in reversed(arr[10, 20, 30, 40, 50]):17    print(item50)
    output50
    All 5 passes — pass 1 is the card above
    passitem
    150
    240
    330
    420
    510
  7. print(" Using slice:")

    19# Or slice20print("\nUsing slice:")21for item in arr[::-1]:
    output
    Using slice:
  8. for item in arr[::-1]:

    pass 1 of 5
    20print("\nUsing slice:")21for item50 in arr[::-1][50, 40, 30, 20, 10]:22    print(item50)
    output50
    All 5 passes — pass 1 is the card above
    passitem
    150
    240
    330
    420
    510

range(start, end, step) with negative step counts backwards.

Step by N (every nth element)

Skip elements by using a step value.

step
step_by_n.py
Replay: real traced execution (multi-file project)
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)
  1. 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:
  2. for i in range(0, 51, step):

    pass 1 of 11
    4print(f"Counting by {step}:")5for i0 in range(0, 51, step5):6    print(i0)
    output0
    All 11 passes — pass 1 is the card above
    passi
    10
    25
    310
    415
    520
    625
    730
    835
    940
    1045
    1150
  3. 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:
  4. for i in range(0, len(names), 2):

    pass 1 of 3
    10print("\nEvery other name:")11for i0 in range(0, len(names['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']), 2):12    print(names[i]Alice)
    outputAlice
    All 3 passes — pass 1 is the card above
    passinames[i]
    10Alice
    22Charlie
    34Eve
  5. print(" Using slice:")

    14# Pythonic: slice with step15print("\nUsing slice:")16for name in names[::2]:
    output
    Using slice:
  6. for name in names[::2]:

    pass 1 of 3
    15print("\nUsing slice:")16for nameAlice in names[::2]['Alice', 'Charlie', 'Eve']:17    print(nameAlice)
    outputAlice
    All 3 passes — pass 1 is the card above
    passname
    1Alice
    2Charlie
    3Eve
  7. 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]
  1. step ← 2

    1step→ 2 = 223# Count by step4print(f"Counting by {step2}:")5for i in range(0, 51, step):
    outputCounting by 2:
  2. for i in range(0, 51, step):

    pass 1 of 26
    4print(f"Counting by {step}:")5for i0 in range(0, 51, step2):6    print(i0)
    output0
    26 passes — pass 1 is the card above
    passi
    10
    22
    34
    46
    58
    610
    712
    814
    916
    ⋯ 15 more passes ⋯
    2548
    2650
  3. 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:
  4. for i in range(0, len(names), 2):

    pass 1 of 3
    10print("\nEvery other name:")11for i0 in range(0, len(names['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']), 2):12    print(names[i]Alice)
    outputAlice
    All 3 passes — pass 1 is the card above
    passinames[i]
    10Alice
    22Charlie
    34Eve
  5. print(" Using slice:")

    14# Pythonic: slice with step15print("\nUsing slice:")16for name in names[::2]:
    output
    Using slice:
  6. for name in names[::2]:

    pass 1 of 3
    15print("\nUsing slice:")16for nameAlice in names[::2]['Alice', 'Charlie', 'Eve']:17    print(nameAlice)
    outputAlice
    All 3 passes — pass 1 is the card above
    passname
    1Alice
    2Charlie
    3Eve
  7. 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]
  1. step ← 10

    1step→ 10 = 1023# Count by step4print(f"Counting by {step10}:")5for i in range(0, 51, step):
    outputCounting by 10:
  2. for i in range(0, 51, step):

    pass 1 of 6
    4print(f"Counting by {step}:")5for i0 in range(0, 51, step10):6    print(i0)
    output0
    All 6 passes — pass 1 is the card above
    passi
    10
    210
    320
    430
    540
    650
  3. 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:
  4. for i in range(0, len(names), 2):

    pass 1 of 3
    10print("\nEvery other name:")11for i0 in range(0, len(names['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']), 2):12    print(names[i]Alice)
    outputAlice
    All 3 passes — pass 1 is the card above
    passinames[i]
    10Alice
    22Charlie
    34Eve
  5. print(" Using slice:")

    14# Pythonic: slice with step15print("\nUsing slice:")16for name in names[::2]:
    output
    Using slice:
  6. for name in names[::2]:

    pass 1 of 3
    15print("\nUsing slice:")16for nameAlice in names[::2]['Alice', 'Charlie', 'Eve']:17    print(nameAlice)
    outputAlice
    All 3 passes — pass 1 is the card above
    passname
    1Alice
    2Charlie
    3Eve
  7. 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.

secret
while_condition.py
Replay: real traced execution (multi-file project)
# 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}")

  1. secret ← 7, guess ← 1, attempts ← 0

    1# Guessing game simulation2secret→ 7 = 7    #@secret=3, 93guess→ 1 = 14attempts→ 0 = 0
  2. guess ← 2, attempts ← 1

    pass 1 of 6
    6while guess1 != secret7:  #?while_condition7    print(f"Trying {guess1}... wrong!")8    guess→ 2 += 19    attempts→ 1 += 1
    outputTrying 1... wrong!
    All 6 passes — pass 1 is the card above
    passguessattempts
    11 20 1
    22 31 2
    33 42 3
    44 53 4
    55 64 5
    66 75 6
  3. 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:
  4. total ← 10, i ← 1

    pass 1 of 3
    18print("\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 += 1
    All 3 passes — pass 1 is the card above
    passdata[i]totali
    1100 100 1
    22010 301 2
    33030 602 3
  5. 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
  1. secret ← 3, guess ← 1, attempts ← 0

    1# Guessing game simulation2secret→ 3 = 33guess→ 1 = 14attempts→ 0 = 0
  2. guess ← 2, attempts ← 1

    pass 1 of 2
    6while guess1 != secret3:7    print(f"Trying {guess1}... wrong!")8    guess→ 2 += 19    attempts→ 1 += 1
    outputTrying 1... wrong!
  3. guess ← 3, attempts ← 2

    pass 2 of 2
    6while guess2 != secret3:7    print(f"Trying {guess2}... wrong!")8    guess→ 3 += 19    attempts→ 2 += 1
    outputTrying 2... wrong!
  4. 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:
  5. total ← 10, i ← 1

    pass 1 of 3
    18print("\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 += 1
    All 3 passes — pass 1 is the card above
    passdata[i]totali
    1100 100 1
    22010 301 2
    33030 602 3
  6. 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
  1. secret ← 9, guess ← 1, attempts ← 0

    1# Guessing game simulation2secret→ 9 = 93guess→ 1 = 14attempts→ 0 = 0
  2. guess ← 2, attempts ← 1

    pass 1 of 8
    6while guess1 != secret9:7    print(f"Trying {guess1}... wrong!")8    guess→ 2 += 19    attempts→ 1 += 1
    outputTrying 1... wrong!
    All 8 passes — pass 1 is the card above
    passguessattempts
    11 20 1
    22 31 2
    33 42 3
    44 53 4
    55 64 5
    66 75 6
    77 86 7
    88 97 8
  3. 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:
  4. total ← 10, i ← 1

    pass 1 of 3
    18print("\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 += 1
    All 3 passes — pass 1 is the card above
    passdata[i]totali
    1100 100 1
    22010 301 2
    33030 602 3
  5. 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.

while Condition-controlled loop: unknown iterations, check before each.

Emulating do-while

Python doesn't have do-while, but you can emulate it.

do_while_emulate.py
Replay: real traced execution (multi-file project)
# 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")

  1. choice ← 0

    3# Pattern 1: while True with break at end4print("=== Pattern 1: while True + break ===")5choice→ 0 = 0
    output=== Pattern 1: while True + break ===
  2. 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_input
    output=== Menu ===
    1. Play
    2. Settings
    3. Exit
    Choice: 0
  3. if choice == 3:

    17if choice3 == 3:18    break
  4. attempts ← 0

    20print("Goodbye!")2122# Pattern 2: Loop-and-a-half23print("\n=== Pattern 2: Loop-and-a-half ===")24attempts→ 0 = 0
    outputGoodbye!
    
    === Pattern 2: Loop-and-a-half ===
  5. attempts ← 1, success ← False

    pass 1 of 3
    26while 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
    passattemptssuccess
    10 1False
    21 2False
    32 3True
  6. if success:

    33if successTrue:34    print("Success!")35    break
    outputSuccess!
  7. 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 ===
  8. while (n := next(numbers, None)) is not None and n != 0:

    pass 1 of 3
    43while (n1 := next(numbers⟨list_iterator A⟩, None)) is not None and n != 0:44    print(f"Processing: {n1}")
    outputProcessing: 1
    All 3 passes — pass 1 is the card above
    passn
    11
    22
    33
  9. 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.

enumerate `for i, item in enumerate(list)` - get index and value together.
zip `for a, b in zip(list1, list2)` - iterate multiple lists in parallel.

Exercise: infinite_patterns.py

Explore intentional infinite loops and how to use them safely