>>> Python for Beginners Chapter 07 of 10

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}")
This is line 0 This is line 1 This is line 2 This is line 3 This is line 4

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}")
1+2+3+4+5 = 15

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!")
3... 2... 1... Lift off!

Looping over text

You can loop straight over a string, one character at a time:

for letter in "Zambia":
    print(letter)
Z a m b i a
โœ๏ธ Try it yourself

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).

Beware the endless loop

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