32 FIRST STEPS
Loopy loops
Computers are great at doing boring tasks without
complaining. Programmers aren’t, but they are good at
getting computers to do repetitive work for them—by
using loops. A loop runs the same block of code over
and over again. There are several different types of loop.
For loops
When you know how many times you want to run a
block of code, you can use a for loop. In this example,
Emma has written a program to make a sign for her
door. It prints “Emma’s Room—Keep Out!!!” ten times. —Keep Out!!!
Emma’s Room
Try out her code for yourself in the shell. (After typing —Keep Out!!!
Emma’s Room
—Keep Out!!!
the code and hitting enter/return, press backspace to Emma’s Room
—Keep Out!!!
Emma’s Room
remove the indent and then hit enter/return again.) —Keep Out!!!
Emma’s Room
—Keep Out!!!
Emma’s Room
—Keep Out!!!
This is the loop The loop runs 10 times. Emma’s Room
—Keep Out!!!
variable. Emma’s Room
—Keep Out!!!
Emma’s Room
—Keep Out!!!
Emma’s Room
—Keep Out!!!
Emma’s Room
>>> for counter in range(1, 11):
print('Emma\'s Room - Keep Out!!!')
Indent the commands in The line that gets repeated
the body 4 spaces. is called the loop body.
▽ Loop variable EXPERT TIPS
The loop variable keeps track of how many times we’ve gone Range
around the loop so far. The first time round it’s equal to the first
number in the list specified by range(1, 11). The second time In Python code, the word “range”
around it’s equal to the second number in the list, and so on. followed by two numbers within
When we’ve used all the numbers in the list, we stop looping. brackets stands for “all the
numbers from the first number to
First loop Second loop Third loop
one less than the second number”.
So range(1, 4) means the
numbers 1, 2, and 3—but not 4.
In Emma’s “Keep Out” program,
range(1, 11) is the numbers
1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.
Loop variable = 1 Loop variable = 2 Loop variable = 3