Gulberg Green, Islamabad

Programming Fundamentals · Lesson 06

Repeating with loops

Use a for loop to repeat work once for each value in a sequence.

A loop repeats a block of instructions. A for loop takes one item at a time from a sequence and assigns it to a name. Python runs the indented block for that item before moving to the next.

The range function supplies a sequence of whole numbers. With two arguments, range starts at the first number and stops just before the second. That means range(1, 4) produces 1, 2, and 3.

Trace a loop by writing the value of its loop variable beside the output for each pass. Once the sequence runs out, Python continues at the first instruction after the indented block.

Read the example

Python 3
for desk in range(1, 4):
    print("Desk", desk)
print("All desks labelled.")
Expected output
Desk 1
Desk 2
Desk 3
All desks labelled.

The first print runs three times because it is indented inside the loop. The last print aligns with for and therefore runs once after the loop finishes.

Try it yourself

Change the loop to print labels for desks 1 through 5. What value should you use for the stopping point?

Show a worked solution
for desk in range(1, 6):
    print("Desk", desk)

Check your understanding

Your lesson quiz

Answer all five questions. Score at least 4 out of 5 (80%) to pass. You can retry as often as you like.

1. Which values does range(1, 4) supply?
2. Which range labels desks 1 through 5?
3. How often does a print outside this completed for loop run?
4. What happens to the loop variable on each pass?
5. How many passes does range(1, 4) produce?

Quiz progress is saved in this browser. View certificates →

Learn together

Was this lesson helpful?

Comments and reactions are not open yet.

WhatsApp