Back to teaching portfolio

Chapter 4 · Repetition Structures

CSBP119 Practical Questions

Loops help students automate repetitive work. These hands-on drills cover while, for, sentinel values, and nested iteration.

Problem 1 · Shuttle Loop

Daily Shuttle Announcer

Simulate a shuttle service that runs from 6:00 to 23:00. For each hour, announce the stops in order.

  1. Use a while loop for the hours.
  2. Inside, loop over stop positions using integers.
  3. Print timestamps such as “08:00 shuttle at Library”.
current_hour = 6

while current_hour < 23:
    stop_index = 0
    while stop_index < 4:
        if stop_index == 0:
            stop_name = "Gate"
        elif stop_index == 1:
            stop_name = "Library"
        elif stop_index == 2:
            stop_name = "Dorms"
        else:
            stop_name = "Sports Complex"
        print(f"{current_hour:02d}:00 shuttle at {stop_name}")
        stop_index += 1
    current_hour += 1
Problem 2 · Practice Drill

Multiplication Trainer

Ask the user multiplication questions until they type “quit”. Track how many answers were correct.

  1. Use while True and break on “quit”.
  2. Prompt separately for the left and right factors.
  3. Check the answer and count successes.
correct = 0

while True:
    command = input("Type 'go' for a problem or 'quit' to stop: ").strip().lower()
    if command == "quit":
        break
    left = int(input("Left factor: "))
    right = int(input("Right factor: "))
    guess = int(input("Answer: "))
    if guess == left * right:
        correct += 1
        print("Correct!")
    else:
        print("Try again.")

print("You solved", correct, "problem(s) correctly.")
Problem 3 · Sentinel Average

Temperature Logger

Read temperature readings until the user enters -99. Compute the average of the values entered.

  1. Use a sentinel-controlled while loop.
  2. Accumulate totals and counts.
  3. Guard against division by zero.
total = 0.0
count = 0

value = float(input("Enter a temperature (-99 to stop): "))
while value != -99:
    total += value
    count += 1
    value = float(input("Enter a temperature (-99 to stop): "))

if count == 0:
    print("No readings provided.")
else:
    print("Average temperature:", round(total / count, 2))