Chapter 07 ยท Repeating
Repeating With Loops
Computers are brilliant at doing boring things many times without complaint. Loops are how you tell them to repeat โ the moment programming starts to feel powerful.
The for loop โ repeat a set number of times
range(n) counts from 0 up to (not including) n. A for loop walks through it:
for number in range(5):
print(f"This is line {number}")
Each time round, number holds the next value. The indented block runs once per value.
Counting from 1
range(1, 6) goes from 1 up to (not including) 6:
total = 0
for n in range(1, 6):
total = total + n
print(f"1+2+3+4+5 = {total}")
The while loop โ repeat until something changes
A while loop keeps going as long as its condition stays true:
count = 3
while count > 0:
print(f"{count}...")
count = count - 1
print("Lift off!")
Looping over text
You can loop straight over a string, one character at a time:
for letter in "Zambia":
print(letter)
Use a for loop to print the 7 times table (7, 14, 21 ... up to 70). Hint:
for n in range(1, 11): print(n * 7).
In a while loop, something inside must eventually make the condition false โ otherwise it
runs forever. In the countdown above, count = count - 1 is what saves us. Forget it and the
program never stops.
Recap
for x in range(n):repeats a fixed number of times.while condition:repeats until the condition becomes false.- You can loop over strings (and, next chapter, lists) directly.