Learning Hub/Python/Session 3

Session 3 of 5 · 60 minutes

Loops

Make the computer repeat work for you with for loops, while loops and range().

Goals

By the end of this session you can:

  • Repeat code a fixed number of times with a for loop and range()
  • Repeat code until something changes with a while loop
  • Keep a running total (an accumulator) inside a loop
  • Stop a loop early with break

Words to know

loop
Code that repeats.
iteration
One trip through the loop.
range()
A function that produces a sequence of numbers to loop over.
accumulator
A variable that collects a result, like a running total.
infinite loop
A loop that never stops because its condition never becomes False.

The lesson

Step 1: The for loop

Imagine printing “Hello” five times by writing print("Hello") five times. A loop does it for you.

Python
for i in range(5):
    print("Hello", i)
Output
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4

range(5) makes the numbers 0, 1, 2, 3, 4. The loop variable i takes each one in turn. Notice:

  • Counting starts at 0, not 1.
  • range(5) stops before 5.
  • The lines inside the loop are indented, just like an if.

Step 2: Start, stop and step

range() can take up to three numbers: where to start, where to stop (not included) and how big each step is.

Python
for n in range(1, 6):
    print(n)
Output
1
2
3
4
5
Python
for n in range(10, 0, -2):
    print(n)
Output
10
8
6
4
2

Step 3: Keeping a running total

A very common pattern: create a variable before the loop, then update it inside the loop.

Python
total = 0
for n in range(1, 5):
    total = total + n
    print("Added", n, "total is", total)

print("Final total:", total)
Output
Added 1 total is 1
Added 2 total is 3
Added 3 total is 6
Added 4 total is 10
Final total: 10

Common mistake: If you write total = 0 inside the loop, it resets to zero on every trip. Set it once, before the loop.

total += n is a shorter way to write total = total + n.

Step 4: The while loop

A for loop runs a set number of times. A while loop runs as long as its condition is true. It is perfect when you don’t know in advance how many times you need.

Python
count = 3
while count > 0:
    print(count)
    count = count - 1
print("Go!")
Output
3
2
1
Go!

The loop changes count each time. If it didn’t, the condition would stay true forever and the program would never stop: an infinite loop. If that happens, press the Stop button in your editor.

Step 5: Stopping early with break

break ends a loop immediately. It is often used with while True, a loop that runs until you tell it to stop.

Python
while True:
    word = input("Type a word (or 'quit'): ")
    if word == "quit":
        break
    print("You typed", word)
print("Bye!")
Output
Type a word (or 'quit'): apple
You typed apple
Type a word (or 'quit'): quit
Bye!

Exercise

Countdown

  1. Use a for loop with range() to print the numbers from 10 down to 1.
  2. After the loop, print Liftoff!
  3. Change your program so the user chooses the starting number with input().
Need a hint?

range(10, 0, -1) counts down from 10 to 1. The third number is the step.

Small project

Times table and total

Build a program that prints a times table and adds up the answers.

  1. Ask the user for a number.
  2. Print its times table from 1 to 10, one line each, like 7 x 3 = 21.
  3. Add up all ten answers in a variable called total and print Total: ... at the end.
  4. Use a while loop to ask again until the user types 0.

Stretch it: Print the times table only for the even multipliers (2, 4, 6, 8, 10).

Quiz

Check your understanding

Pick one answer for each question. Your score appears right in the page; nothing is sent anywhere.

  1. Question 1How many times does this loop run?for i in range(3): print("hi")
  2. Question 2What is the last number printed by for n in range(1, 5): print(n) ?
  3. Question 3What does a while loop do?
  4. Question 4What is wrong with this loop?x = 1 while x > 0: print(x)
  5. Question 5Which keyword stops a loop immediately?