Loops, and where your data lives

INPUT · Slides

Repeating a set number of times

01 / 07

Writing it three times is a chore

You want a greeting on the screen three times. With what you know so far, this is the only way to write it.

Three is bearable. But what about a hundred? A thousand? Copying one line out over and over runs out of road very quickly.

print("hello")print("hello")print("hello")

Result

hello
hello
hello

02 / 07

The shape of for and range

What you use instead is for, the writing for repeating.

  • after for comes the variable that receives
  • after in comes range(3), which decides how many times
  • end the line with : and write the body underneath, indented four spaces

The colon and the indent are exactly as they were for if. The indented lines are the ones that get repeated.

for i in range(3):    print("hello")

Result

hello
hello
hello

03 / 07

What is in i

i is an ordinary variable, and its contents are swapped for the next one on every go. Show it and find out what is in there.

Out come 0, 1 and 2. The thing to notice is that it starts at 0, not at 1.

The name i is the habit for a loop counter. You are free to use a name you find clearer, like count.

for i in range(3):    print(i)

Result

0
1
2

04 / 07

range(3) does not include the 3

range(3) makes three things: 0, 1 and 2. The 3 itself is not in there.

"It goes round three times" and "a 3 comes out" are two different statements. Everybody trips here the first time. The count is right, the last number is one short — remember it that way.

for i in range(4):    print(i)

Result

0
1
2
3

05 / 07

Choosing where to start

You can hand range two numbers separated by a comma. Then it runs from the start up to just before the end.

range(1, 4) gives 1, 2 and 3. Here too, the second number is left out. Use this when you want to count from 1.

for i in range(1, 4):    print(i)

Result

1
2
3

06 / 07

Inside the loop and outside it

Just as with if, only the indented lines are repeated. A line brought back to the left margin runs once, after the repeating has finished.

What you put inside changes everything. The indent is what decides the reach of the loop.

for i in range(3):    print(i)print("done")

Result

0
1
2
done

07 / 07

You can do sums inside a loop

What goes inside is not limited to print. You can write over a variable as well.

The example below sets up a container holding 0 first, then adds i into it on every go. Show it once the repeating is over and you have the total.

This shape — set up the container outside, add into it inside — comes up from here on for ever, so learn it now.

total = 0for i in range(1, 4):    total += iprint(total)

Result

6