Skip to content

Module 6 · Loops and Iteration — topic 1 of 12

Why loops are required

Loops let a program repeat work without repeating code. See the problems that copy-pasted code causes, the two kinds of loop Python offers, and how to recognise a task that needs a loop.

Beginner 10 min read·Lesson 70 of 306 in Python Programming

Learning objectives

  • Explain the problems loops solve
  • Distinguish count-controlled and condition-controlled repetition
  • Recognise repetition in a task description

Definition

Loops let a program repeat work without repeating code. See the problems that copy-pasted code causes, the two kinds of loop Python offers, and how to recognise a task that needs a loop.

Introduction

Imagine printing a multiplication table, checking a hundred student records or asking for a password until it is correct. Writing the same line over and over would be tedious and fragile. A loop tells Python to repeat a block of code as many times as needed.

Each repetition is called an iteration. Python has two loop statements: for, which goes through the items of a collection or a range of numbers, and while, which repeats as long as a condition stays true.

Why it matters

Computers are valuable precisely because they repeat work quickly and without getting tired. Loops are how you harness that. Almost every program that processes data, waits for input or runs a game uses at least one loop.

Detailed explanation

Copy-pasted code is hard to change: to adjust the behaviour you must edit every copy, and it is easy to miss one. It also can’t adapt to data whose size you don’t know in advance, such as a list read from a file.

Count-controlled repetition: you know how many times, or which items, to process. Use for: for each student in the list; for each number from 1 to 10.

Condition-controlled repetition: you repeat until something happens and don’t know in advance how many times. Use while: while the guess is wrong; while there are tasks left.

Signals in a task description that suggest a loop: “for each”, “every”, “until”, “repeat”, “keep asking”, “all the”.

A loop has a body (the indented block that repeats), a way to move forward (the next item, or a changing variable), and a way to stop (no items left, or the condition becoming false).

Syntax

Text
for item in collection:
body
while condition:
body
  • for repeats once per item.
  • while repeats while the condition is true.
  • The indented body is what repeats.

Code examples

Without and with a loop

Python
print("Reminder 1")
print("Reminder 2")
print("Reminder 3")
for n in range(1, 4):
print("Reminder", n)
Output
Reminder 1
Reminder 2
Reminder 3
Reminder 1
Reminder 2
Reminder 3

A table in three lines

Python
for n in range(1, 6):
print(f"7 x {n} = {7 * n}")
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

More examples

Processing data of any size

Python
marks = [72, 45, 88, 39, 91, 60]
total = 0
failed = 0
for m in marks:
total += m
if m < 40:
failed += 1
print("Students:", len(marks))
print("Average:", round(total / len(marks), 1))
print("Failed:", failed)
Output
Students: 6
Average: 65.8
Failed: 1

Step-by-step explanation

  • total and failed start at zero before the loop.
  • The for loop visits every mark once, whatever the length of the list.
  • Each iteration adds the mark to total and counts it if it is below 40.
  • After the loop, the results are printed once.

Expected output

Running “Processing data of any size” prints exactly:

TextOutput
Students: 6
Average: 65.8
Failed: 1

Practical applications

  • Payroll software loops over every employee to compute salaries.
  • Web servers run a loop that waits for and answers requests.
  • Games redraw the screen in a loop many times per second.

Best practices

  • Use for when processing every item of a collection.
  • Use while when stopping depends on a condition.
  • Initialise counters and totals before the loop and report after it.

Common mistakes

Copy-pasting instead of looping

Avoid

Five near-identical print lines with different numbers.

Prefer

for n in range(5): print(...)

Copies must each be edited when requirements change; a loop changes in one place.

Putting the summary inside the loop

Avoid

for m in marks:
total += m
print(total / len(marks))

Prefer

for m in marks:
total += m
print(total / len(marks))

Indentation decides what repeats; the average should be printed once, after the loop.

Key takeaways

  • Loops repeat a block of code; each repetition is an iteration.
  • for is for items or counts; while is for conditions.
  • Loops adapt to data of any size.

Try it yourself

  1. 1
    Print the squares of the numbers 1 to 10 with a loop.
  2. 2
    Given a list of prices, count how many are above 500.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

13 questions cover the “Loops and Iteration” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module