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
for desk in range(1, 4):
print("Desk", desk)
print("All desks labelled.")
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.
Quiz progress is saved in this browser. View certificates →
Learn together
Was this lesson helpful?
Comments and reactions are not open yet.
Join the conversation
Ask a question or share what you learned. Your display name and comment will be public after review. Please leave out private information. How feedback is stored