BeginnerLesson 6 of 305 min read

Loops: for, while, range and repeating work

Repeat tasks with for and while loops, use range, enumerate and zip, control loops with break and continue, and build lists with comprehensions.

In this lesson you will

  • Write for loops with range
  • Loop directly over items with enumerate and zip
  • Use while, break and continue
  • Build lists with comprehensions

About 19 minutes

Let the computer do the boring part

A teacher asks you to write “I will not talk in class” one hundred times. You could write it by hand, or you could say: “repeat this 100 times”. That second sentence is a loop. Computers never get tired or bored, so repeating work is what they do best. A loop lets you handle a list of 10 items or 10 million with the same few lines.

The for loop

for i in range(1, 6):
    print("Round", i)
Round 1
Round 2
Round 3
Round 4
Round 5

A for loop takes each item from a sequence, one at a time, puts it in the variable you name (here i), and runs the indented block. range(1, 6) produces the numbers 1, 2, 3, 4, 5. It starts at the first number and stops before the second, just as slices do.

range() in three forms

print(list(range(5)))          # 0 to 4
print(list(range(2, 7)))       # 2 to 6
print(list(range(0, 20, 5)))   # step by 5
print(list(range(5, 0, -1)))   # count down
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6]
[0, 5, 10, 15]
[5, 4, 3, 2, 1]
for n in range(1, 6):
    print(f"7 x {n} = {7 * n}")
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Looping over things directly

fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print("I like", fruit)

for letter in "Hi!":
    print(letter)
I like apple
I like banana
I like mango
H
i
!

This is a Python favourite: loop straight over the items instead of using positions. If you also need the position, ask for it with enumerate.

colours = ["red", "green", "blue"]

for position, colour in enumerate(colours, start=1):
    print(position, colour)

names = ["Sara", "Ali", "Mina"]
scores = [90, 72, 85]
for name, score in zip(names, scores):
    print(f"{name}: {score}")
1 red
2 green
3 blue
Sara: 90
Ali: 72
Mina: 85

Adding things up: the accumulator pattern

total = 0
for n in range(1, 101):
    total += n
print(total)          # 5050

prices = [120, 45, 300]
bill = 0
for p in prices:
    bill += p
print("Bill:", bill)
5050
Bill: 465

This pattern, a starting value that you update inside the loop, is everywhere. Start with an empty total, an empty list, or the first item, and build the answer piece by piece. (Python also has sum(prices) as a shortcut, but the loop teaches the idea.)

The while loop

Use while when you do not know in advance how many rounds are needed. It keeps going as long as its condition is True.

money = 100
days = 0

while money > 0:
    money -= 30
    days += 1

print(f"The money lasted {days} days")
The money lasted 4 days
Common mistake

An infinite loop: the condition never becomes false because nothing changes the variable. while True: without a way out freezes your program. If it happens, press Ctrl + C in the terminal to stop it. Always ask: what makes this loop end?

break and continue

for i in range(1, 11):
    if i == 3:
        continue      # skip this round
    if i == 6:
        break         # leave the loop completely
    print(i)
1
2
4
5
  • break ends the whole loop immediately.
  • continue skips the rest of this round and jumps to the next one.

A very common pattern is a loop that runs “forever” and uses break to leave when the user is done:

while True:
    answer = input("Type quit to stop: ")
    if answer == "quit":
        break
    print("You typed:", answer)
print("Goodbye")
Type quit to stop: hello
You typed: hello
Type quit to stop: again
You typed: again
Type quit to stop: quit
Goodbye

else on a loop

for n in range(2, 8):
    if n == 10:
        print("found ten")
        break
else:
    print("no ten in the range")
no ten in the range

Loops inside loops

for row in range(1, 4):
    line = ""
    for col in range(1, 5):
        line += "* "
    print(line)
* * * * 
* * * * 
* * * * 

The inner loop completes fully for every round of the outer loop: 3 rows times 4 columns gives 12 stars. Nested loops handle tables, grids and games.

A classic exercise: FizzBuzz

for i in range(1, 16):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

List comprehensions: a loop in one line

squares = [n * n for n in range(1, 6)]
print(squares)

evens = [n for n in range(1, 11) if n % 2 == 0]
print(evens)

shout = [w.upper() for w in ["a", "b", "c"]]
print(shout)
[1, 4, 9, 16, 25]
[2, 4, 6, 8, 10]
['A', 'B', 'C']

A list comprehension builds a new list in a single readable line. Read it as: “n times n, for each n in the range”. Use it when the loop only builds a list; use a normal loop when you have several steps.

Practice

Print all the multiples of 7 up to 70 on one line, separated by spaces. Hint: print(..., end=" ") stays on the same line.

Show one possible answer
for n in range(7, 71, 7):
    print(n, end=" ")
print()
7 14 21 28 35 42 49 56 63 70 
Practice

Ask the user for numbers repeatedly until they type 0, then print the sum of all numbers entered.

Show one possible answer
total = 0
while True:
    n = int(input("Number (0 to stop): "))
    if n == 0:
        break
    total += n
print("Sum:", total)
Number (0 to stop): 5
Number (0 to stop): 10
Number (0 to stop): 3
Number (0 to stop): 0
Sum: 18
Choose the right loop

Use for when you are going through a collection or a known count. Use while when you repeat until a condition changes. Most Python code uses for.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does list(range(2, 6)) give?

  1. [2, 3, 4, 5, 6]
  2. [3, 4, 5]
  3. [2, 6]
  4. [2, 3, 4, 5]

range stops before the end value.

Which keyword leaves a loop immediately?

  1. break
  2. continue
  3. pass
  4. stop

break ends the loop.

When is a while loop the better choice?

  1. Always
  2. Only for strings
  3. When you don’t know how many rounds are needed
  4. Never

while repeats until a condition changes.

What does [n * 2 for n in [1, 2, 3]] give?

  1. [1, 2, 3]
  2. [6]
  3. [2, 3, 4]
  4. [2, 4, 6]

It doubles each number.

How do you stop an infinite loop in the terminal?

  1. Ctrl + Z only
  2. Ctrl + C
  3. Close the keyboard
  4. You can’t

Ctrl + C interrupts the program.

Summary

  • for loops go through a sequence; range makes number sequences.
  • while repeats until a condition changes.
  • break leaves, continue skips.
  • List comprehensions build lists in one line.

Next lesson

Next: lists and tuples, collections of many values.

Questions

Why does range(5) stop at 4?

range stops before its end value, so range(5) gives 0 to 4, which is five numbers.

What does pass do?

It is a placeholder that does nothing, useful where Python needs a block but you have no code yet.

Is a for loop faster than a while loop?

Usually for loops are clearer and a little faster. Choose by readability.

Progress is saved in this browser.