Programming in Python · Lesson 7

Repetition Control Structures — Programming Examples

Six runnable Python examples covering for-loops, range(), user-controlled loops, counters, accumulators, nested loops, while-loops with input validation, and infinite loops with break.

  • loops
  • for-loops
  • range
  • counters
  • accumulators
  • nested-loops
  • while-loops
  • infinite-loops
  • break

Use these short, runnable examples as demonstration checkpoints. Ask students to predict the output before you run each one.

  1. Count-controlled for-loops and the range() function
# range(stop), range(start, stop), and range(start, stop, step)
print("range(5):")
for i in range(5):
    print(i)

print("range(1, 6):")
for i in range(1, 6):
    print(i)

print("range(0, 21, 5):")
for i in range(0, 21, 5):
    print(i)

# The loop body repeats once for every value in the sequence
print("Warm-up:")
for i in range(1, 4):
    print("Stretch")
    print("Breathe")
    print()

Teaching point: A for-loop is a count-controlled loop: the loop counter i visits each value in the iterative sequence that range() builds. range(5) starts at 0 by default, range(1, 6) sets the start, and range(0, 21, 5) adds an increment. The ending number is never included, so range(1, 4) repeats three times. Ask students how many numbers range(5) produces before running it.

  1. User-controlled loop
laps = int(input("How many laps will you swim? "))

# The user's answer becomes the stopping value for range()
for i in range(laps):
    print("Swim to the wall and back.")

print("Workout complete:", laps, "laps.")

Teaching point: In a user-controlled loop, the user’s input sets the value passed to range() at runtime, so the number of repetitions is not known when the program is written. Convert the input with int() first, because range() needs a whole number. Run it with 3, then with 0 to show that the body never runs.

  1. Counters and accumulators: step tracker
total_steps = 0      # accumulator starts at 0
goal_days = 0        # counter starts at 0
day_number = 0       # separate output counter

days = int(input("How many days did you track? "))
for i in range(days):
    day_number += 1
    steps = int(input("Steps on day " + str(day_number) + ": "))
    total_steps = total_steps + steps
    if steps >= 10000:
        goal_days += 1
    print("Running total:", total_steps)

print("Total steps:", total_steps)
print("Days at 10,000 or more:", goal_days)

Build sequence:

  1. Start with only the for-loop and the steps input, printing each value.
  2. Add total_steps = 0 above the loop and total_steps = total_steps + steps inside it, and point out the two parts of every accumulator.
  3. Add the goal_days counter with the if statement.
  4. Add day_number as a separate output counter instead of printing i, and explain why the book recommends not reusing the loop counter.

Teaching point: An accumulator takes two steps: set it to a starting value (0 for addition) before the loop, then add to it inside the loop. A counter works the same way but adds 1 each time. The book recommends a separate variable such as day_number for output instead of reusing the loop counter i, so the loop counter is never changed by accident. Initializing an accumulator inside the loop is a common bug: it resets to 0 on every pass.

  1. Nested loops: multiplication table
size = int(input("Table size: "))

# Outer loop: one row per value of r
for r in range(1, size + 1):
    row = ""
    # Inner loop: runs completely for every pass of the outer loop
    for c in range(1, size + 1):
        row = row + str(r * c) + "\t"
    print(row)

Teaching point: In a nested loop, the inner loop runs completely for every single pass of the outer loop. Each loop needs its own counter variable; by convention the outer one is often i or r and the inner one j or c. With a size of 4, the outer loop runs 4 times and the inner statement runs 4 x 4 = 16 times. The variable row is a string accumulator that starts as “” and grows inside the inner loop.

  1. Pre-test while-loop with an exit option
score = int(input("Enter a quiz score (0-100): "))

# Pre-test loop: repeats only while the input is invalid
while (score < 0 or score > 100) and score != 999:
    score = int(input("Try again. Enter 0 to 100, or 999 to quit: "))

if score == 999:
    print("No score recorded. Bye.")
else:
    print("Score", score, "recorded.")

Teaching point: A while-loop is a condition-controlled pre-test loop: it checks its condition first and runs only while the condition is True, which makes it ideal for validating input. Every pass must give the user a way to change the condition. Leave out the score = part of the line inside the loop to show an infinite loop (stop it with Ctrl+C). The 999 exit value is built into the loop condition, which the book prefers over a break statement because a break can let the program continue with an invalid value.

  1. Infinite loop with an if statement and break
# while True never becomes False on its own: this is an intentional infinite loop
while True:
    seats_text = input("How many seats do you want to reserve (1-8)? ")

    # The if statement is the only way out of the loop
    if seats_text.isdigit() and int(seats_text) >= 1 and int(seats_text) <= 8:
        break

    print("Invalid entry. Enter a whole number from 1 to 8.")

seats = int(seats_text)
print("Reserved", seats, "seats.")

Teaching point: while True: creates an infinite loop on purpose, because the condition can never become False. The only exit is the if statement inside the loop: when the input passes isdigit() and the 1 to 8 range check, break jumps out of the loop and the program continues with the first statement after it. Any invalid entry skips the break, prints the error, and repeats. Compare it with Example 5: there the exit is built into the loop condition, which the book prefers, while here the exit lives in the loop body. Both are valid, but with break you have to check that every path out of the loop leaves the variables in a usable state. Run it with ten, 0, 12, and then 4.

Exit-ticket prompts

  1. How many numbers are in range(2, 11, 2), and what are they?
  2. In Example 3, what goes wrong if total_steps = 0 is moved inside the for-loop?
  3. In Example 4 with a size of 3, how many times does the inner statement run?
  4. Why does this loop never end? while reps < 1 or reps > 25: int(input(“Try again: “))
  5. Write a for-loop that prints 10, 20, 30, 40, 50.

Answer key

  1. Five: 2, 4, 6, 8, 10.
  2. It resets to 0 on every pass, so the final total is only the last day’s steps.
  3. 9 times (3 outer passes x 3 inner passes).
  4. The new input is never assigned back to reps, so the condition never changes.
  5. for i in range(10, 51, 10): print(i)