Python Quest

Track 4 · Lesson 1 of 11

Why loops? Repeating work with for

Use a for loop over range() to repeat a block of code a set number of times, and use the loop variable inside it.

About 25 minFirst steps3 exercisesFree

You will be able to

  • Explain why programs need repetition instead of copied lines
  • Write a for loop over range(n) that repeats a block n times
  • Use the loop variable to make each repetition different
  • Tell which lines are inside the loop body and which run once afterwards

Imagine you run the front desk at Palm Court Clinic. Every morning you print a numbered ticket for each patient: Ticket 1, Ticket 2, and so on. On a quiet day that's 5 tickets. On a busy day it's 60. You could write 60 print() lines, but then the program only works on days with exactly 60 patients.

What you need is a way to say "do this N times" — where N can change every day. That is what a loop does. A loop runs the same block of code again and again, and each pass through the block is called an iteration. In this lesson you'll write your first loops with Python's for statement.

Repeat a line five times
for i in range(5):
    print("Checking the waiting room...")

print("All rounds done.")

Try it: Change 5 to 3 and run it again. Then change it to 0. How many lines appear now?

Let's read that loop piece by piece:

  • for starts the loop.
  • range(5) produces the whole numbers 0, 1, 2, 3, 4 — five values, starting at 0.
  • i is the loop variable. Before each iteration Python stores the next value from range(5) in it.
  • The colon : ends the loop header, like the colon after if.
  • The indented lines underneath form the loop body. They run once per value.
  • print("All rounds done.") is not indented, so it is not part of the loop. It runs once, after the loop has finished.

Indentation decides what is inside the loop. Use 4 spaces, the same as in an if block.

Using the loop variable

The loop variable changes on every iteration, so you can use it to make each pass different. Because range() starts at 0, people usually add 1 when they want to count from 1:

Number each ticket with the loop variable
patients = 4

for i in range(patients):
    print("Ticket", i + 1)

print("Printed", patients, "tickets")

Try it: Remove the + 1 and run it. Which ticket numbers do you get now?

Python works through this like a person following instructions:

Iterationvalue of iprinted
1st0Ticket 1
2nd1Ticket 2
3rd2Ticket 3
4th3Ticket 4

After the 4th iteration range(4) has no values left, so the loop ends and Python carries on with the next unindented line. A table like this, showing variables at each step, is called a trace table. You'll use them throughout this track to understand what a loop is doing.

The number of repetitions can come from input(). Remember that input() always gives you text, so convert it with int() before passing it to range().

The number of repetitions comes from the user
count = int(input())

for i in range(count):
    print("Reminder", i + 1, "sent")
Input given to the program: "3"

Try it: Run it and type a different number when asked. What happens if you type 0?

Predict the output

for i in range(3):
    print(i * 10)
    print("next")
print("finished")

The loop variable doesn't have to be called i. Choose a name that describes the value: for day in range(7): reads better in a weekly report. When you don't use the variable at all, many Python programmers name it _ to say "I only need the repetition".

Guided practice · ●difficulty 1 of 5 · about 4 min

Print numbered tickets

Palm Court Clinic needs a ticket for every patient booked today.

Read the number of patients with int(input()). Then print one line per patient, numbered from 1, followed by a summary line:

Ticket 1
Ticket 2
Ticket 3
Printed 3 tickets

If there are 0 patients, print only Printed 0 tickets. Use a for loop.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Challenge · ●●difficulty 2 of 5 · about 5 min

A times table for any number

A primary school teacher, Ms Rania Haddad, wants to print a times table for whatever number she types.

Read a whole number with int(input()) and print its table from 1 to 10, in this format (for 7):

7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70

All 10 lines must be printed, one per multiplier.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Debugging · ●●difficulty 2 of 5 · about 4 min

The report that repeats itself

A warehouse supervisor wrote this program to log the safety checks for each shift. For 3 shifts it should print:

Shift 1 checked
Shift 2 checked
Shift 3 checked
All 3 shifts checked

Instead, the supervisor sees Shift 3 checked three times, and the All ... checked line appears after every shift. Find and fix the bugs. The number of shifts is read from input.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Summary

  • A loop repeats a block of code; each pass is an iteration.
  • for i in range(n): runs the indented body n times, with i taking the values 0 to n - 1.
  • The loop variable is different on each iteration — use it (often as i + 1) to number things.
  • Indentation decides what is inside the loop. Unindented lines after the loop run once, when it finishes.
  • range(0) is empty, so the body runs zero times — no special case needed.