← Back to modules

Module

Looping

Learn how computers repeat actions efficiently using loops, then practice tracing and debugging repetition patterns in Python.

1. Why loops matter

Stop repeating yourself

A loop repeats code for you. Instead of writing the same instruction again and again, you write it once and let the computer execute it across many values.

This matters for readability, fewer mistakes, and scalability. If tomorrow you need 1,000 repetitions instead of 10, a loop handles it with a tiny change.

Compare the two styles:

# Repetition by hand (hard to scale)
print("Practice")
print("Practice")
print("Practice")

# Repetition with a loop (easy to scale)
for _ in range(3):
    print("Practice")

2. Loop anatomy

Initializer, condition, update, body

Every loop has four mental parts:

  • Initializer: starting value (for example, count = 0)
  • Condition: rule that decides whether to continue
  • Body: work done each iteration
  • Update: change that moves toward stopping
Iterationvaluerunning_totalCondition before next run
133still True
258still True
3210becomes False

3. for loops

Loop through ranges and lists

Use a for loop when you know what to iterate over, such as a list or a numeric range.

Two common patterns are counting and running totals.

# Count from 1 to 10
for number in range(1, 11):
    print(number)

# Sum a list of quiz scores
scores = [84, 91, 77]
total = 0
for score in scores:
    total += score

Loop Trace Visualizer

Choose a loop pattern and inspect every iteration.

Python example

total = 0
for value in range(1, 6, 1):
    total += value
Iterationvaluerunning_total
111
223
336
4410
5515

Final total: 15


4. while loops

Repeat until a condition changes

Use while when repetition depends on a condition that may change at runtime, such as waiting for valid input.

Inside loops, break exits early and continue skips to the next iteration.

# Validate input until user enters y/n
answer = ""
while answer not in ["y", "n"]:
    answer = input("Continue? (y/n): ")

# Nested loop pattern: 2x3 grid
for row in range(2):
    for col in range(3):
        print(f"({row}, {col})")
Common loop bugs to watch for
  • Off-by-one errors (for example, expecting range end to be included)
  • Missing update step in a while loop
  • Condition that never becomes False

5. practice

Predict the output

Reading loop code and predicting behavior is one of the fastest ways to improve your debugging skills.

Question 1 of 5

What prints from `for i in range(1, 5): print(i)`?


6. debugging

Fix an infinite loop

A loop only stops when its condition eventually becomes False. Use this mini-lab to practice matching your update step with your condition.

Infinite Loop Fixer

Goal: make the loop run exactly 5 times, then stop.

Current loop

count = 0
while count < 5:
    print(count)
    count = count

Iterations run: 30

Final count value: 0

First values printed: 0, 0, 0, 0, 0, 0, 0, 0...


Guided Project

Build a Scoreboard Analyzer

Create a small Python program that analyzes game scores and prints a clear summary. You will combine a for loop, conditionals, and a while loop for repeated threshold checks.

Starter state

scores = [12, 18, 9, 25, 14]
target_score = 15

# TODO: build your analyzer using loops

Scoreboard Analyzer Checklist

  1. 1.Create a scores list with at least 5 integer values.
  2. 2.Use a for loop to compute total_points and score_count.
  3. 3.Inside the same loop, track highest_score and count scores above target_score.
  4. 4.Compute and print the average after the loop (total_points / score_count).
  5. 5.Add a while loop that asks for a new target_score and reruns the above-threshold count.
  6. 6.Stop the while loop when the user enters q.
  7. 7.Print a clean final report showing total, average, highest, and above-target count.