Printing a word ten times with ten print lines is tiring, and impossible for a thousand. A for loop repeats the indented lines under it as many times as you say:
for count in range(5):
print("warm")warm warm warm warm warm
The pattern is for variable in range(number): with a colon, and the repeated lines are indented 4 spaces, just like if. A line after the loop with no indent runs once, after the loop ends.
for i in range(3):
print("Hello")
print("Done")Hello Hello Hello Done
The loop variable
range(5) produces the numbers 0 to 4 and hands them to the loop variable one at a time. You can print it or use it in a calculation:
for i in range(5):
print(i)0 1 2 3 4
range(5) does not include 5, but it still repeats exactly 5 times.Start, stop and step
Give range two numbers to set the start and stop, or three numbers to also set the step (how much to add each time):
| Code | Values of i | Times |
|---|---|---|
| range(3) | 0, 1, 2 | 3 |
| range(1, 3) | 1, 2 | 2 |
| range(1, 6) | 1, 2, 3, 4, 5 | 5 |
| range(0, 10, 2) | 0, 2, 4, 6, 8 | 5 |
| range(10, 0, -3) | 10, 7, 4, 1 | 4 |
for i in range(1, 4):
print("Round " + str(i))
for i in range(10, 0, -3):
print(i)Round 1 Round 2 Round 3 10 7 4 1
A loop can contain an if, which is checked on every turn. Here an extra message is printed on the turn where i is 2:
for i in range(4):
print("vocal warm-up")
if i == 2:
print("tongue twister practice")vocal warm-up vocal warm-up vocal warm-up tongue twister practice vocal warm-up
Practice
Complete the first line so warm is printed 10 times, using the variable count.
for ___:
print("warm")Press Run to see the result. Print Yay 7 times with a for loop and the variable i.
Press Run to see the result. Print She sells seashells twice using range(1, 3).
Press Run to see the result. The program prints sandwich 5 times. Inside the loop, add: if i is 1, print water bottle.
for i in range(5):
print("sandwich")Press Run to see the result. Print the even numbers from 2 to 10, one per line, using range with three numbers.
Press Run to see the result. Rocket countdown: print the numbers from 5 down to 1, then print Launch! once after the loop.
Press Run to see the result. Key points
for i in range(n):repeats the indented lines n times, with i from 0 to n−1.range(a, b)goes from a to b−1;range(a, b, step)adds step each time.- An unindented line after the loop runs once, after the loop ends.