Skip to content

07 Loops

Loops help us repeat a task without writing the same line many times.

Run in Binder Open in Colab Download notebook

Read here. Practice in a notebook.

This page shows the original notebook. Open Binder or Colab to run and edit cells. Work one cell at a time: some examples are deliberately broken for debugging practice. Download your work before leaving Binder; its sessions are temporary.

View original source

Learning Objectives

By the end, you should be able to:

  • Explain that loops repeat code.
  • Use a for loop with range().
  • Explain that range(n) repeats n times.
  • Use a loop to collect repeated input and calculate a total.

Concept Introduction (no code first)

A loop allows a program to repeat a task multiple times instead of writing the same code again and again. Examples include repeated login attempts and repeated system checks.

First Loop Example

Think Before You Run: How many times will the message print?

# This loop repeats the indented line 3 times.
for count in range(3):
    print("System check complete")

Understanding range()

range(5) means repeat 5 times. Keep this idea simple for now: the number inside range() tells Python how many repeats to make.

Think Before You Run: If range(4) is used, how many times will this run?

# range(4) repeats 4 times.
for step in range(4):
    print("Checking login attempt")

Loop Variable

The loop variable changes each time the loop runs. With range(5), it changes from 0 to 4.

# The loop variable is named attempt here.
for attempt in range(3):
    print("Attempt number:", attempt)

Think Before You Run: What is the first value of i?

# i changes from 0 to 4.
for i in range(5):
    print(i)

Think Before You Run

This version adds 1 so the display starts at 1 instead of 0. What numbers do you expect to see?

# Add 1 when you want people-friendly numbering.
for attempt in range(3):
    print("Login attempt:", attempt + 1)

Guided Practice

Change the number inside range() and run the cells again. Watch how the number of printed lines changes.

Think Before You Run: What will be printed if you change range(5) to range(2)?

# TODO: Change 5 to another number.
for check in range(5):
    print("Running classroom computer check")
# TODO: Change the message and the number of repeats.
for entry in range(3):
    print("Enter sample value", entry + 1)

Real-World Examples

Loops are useful when an IT task repeats. Examples include login attempts, system monitoring, and repeated system checks.

# Example 1: login attempts
for attempt in range(3):
    print("Allowed login attempt:", attempt + 1)

# Example 2: system checks
for system_number in range(4):
    print("Checking system", system_number + 1)

# Example 3: repeated data entry reminder
for form_number in range(2):
    print("Enter data for form", form_number + 1)

Loop Visualization

A loop follows a simple pattern:

Start loop
Repeat 1: run the indented code
Repeat 2: run the indented code
Repeat 3: run the indented code
Loop ends

Each repeat is called an iteration, but you can think of it as one loop step.

Loop variable example:

i = 0 -> print
i = 1 -> print
i = 2 -> print
...

range(5) produces 0, 1, 2, 3, 4 which is 5 values.

# Watch the loop steps appear one at a time in the output.
for step in range(3):
    print("Loop step:", step + 1)

print("Loop finished")

Common Mistakes

Python loops depend on indentation and correct range() values. Common mistakes include indentation errors, misunderstanding range(), and off-by-one errors.

Indentation mistake:

# Broken
for item in range(3):
print("Check item")

# Fixed
for item in range(3):
    print("Check item")

Off-by-one reminder:

# range(5) repeats 5 times, but the loop variable is 0, 1, 2, 3, 4.
# Correct pattern to copy when you are unsure.
for number in range(3):
    print("Displayed number:", number + 1)

Parsons Problem

The lines below are scrambled. Put them in the correct order in the next cell.

    print("Checking system", system + 1)
for system in range(3):
print("All checks complete")
# TODO: Reorder the scrambled lines from above.
# The indented line belongs inside the loop.

for system in range(3):
    print("Checking system", system + 1)

print("All checks complete")

Mini Lab

Use repeated input to collect three numbers and calculate a total. The input line repeats each time the loop runs.

# Mini Lab: repeated input and total
# Step 1: Start the total at 0.
# Step 2: Repeat input 3 times.
# Step 3: Add each value to the total.
# Enter three small numbers, one at a time.

total = 0

for entry in range(3):
    value_text = input("Enter a number: ")
    value = float(value_text)
    # Add the new value to the running total.
    total = total + value

print("Total:", total)

Wrap-Up

Loops repeat tasks efficiently. The loop variable changes each time the loop runs.

Next, you will use loops with lists to process collections of data.

Reflection

What repeated task in your field, job, or daily life could a loop help with?