Thirty friends, one message
You want to send "Happy birthday" to 30 friends. Would you type it 30 times?
No. You would find a way to repeat the job. A program can repeat steps too. It can do it 30 times, or a million times, without getting tired.
Key words
| Word | What it means | Example |
|---|---|---|
| Loop | A part of a program that repeats. | for, while |
| Iteration | One run through a loop. It also means repeating steps. | the loop runs 5 times |
| Count-controlled loop | A loop that runs a set number of times. | for i in range(5) |
| Condition-controlled loop | A loop that runs while a condition is True. | while saved < 50 |
| for | The Python word for a count-controlled loop. | |
| while | The Python word for a condition-controlled loop. | |
| range() | Makes the numbers a for loop counts through. | range(5) gives 0 to 4 |
| Infinite loop | A loop that never stops, because its condition never becomes False. | |
| Variable | A name that holds a value. | saved = 0 |
| Function | A named piece of code that does one job. | print() |
| Trace table | A table where you write the value of each variable after each step. |
The cells students fill in are left blank in this preview.
Count-controlled: the for loop
You know how many times to repeat. Use a for loop.
This is a count-controlled loop. Each run through the loop is one iteration. The function range(5) gives the numbers 0, 1, 2, 3 and 4. That is five iterations. In for i in range(5), the name i holds the current number.
Try it: a for loop
for i in range(5):
print("Happy birthday, friend number", i)
# Change 5 to 8 and run it again.
# Notice that the counting starts at 0.
What range() gives you
| You write | The loop counts | How many times |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | 5 |
| range(1, 6) | 1, 2, 3, 4, 5 | 5 |
| range(3) | 0, 1, 2 | 3 |
The cells students fill in are left blank in this preview.
range() with two numbers
data-callouts.note.label
You can give range() two numbers: where to start and where to stop. The loop counts up by 1 and stops before the stop number.
Extra: range() with three numbers
| Code | Numbers it gives | How it works |
|---|---|---|
| range(0, 10, 2) | 0, 2, 4, 6, 8 | Start at 0. Go up by 2. Stop before 10 |
| range(3, 0, -1) | 3, 2, 1 | Start at 3. Go down by 1. Stop before 0 |
The cells students fill in are left blank in this preview.
Quick check: for loops
Have a go
Quick check: for loops
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
Try it: loop over a list
names = ["Sam", "Aisha", "Tom"]
for name in names:
print("Happy birthday,", name)
# A loop can also build a list. Start with an empty list. Then use append to add to the end.
# i * i means i times i.
squares = []
for i in range(1, 6):
squares.append(i * i)
print(squares)