The Hundred Hellos: Python loops comic

LearnFun Comics#2
Sir Oops-a-Lot

The Hundred Hellos

One knight. One hundred guests. One very tired keyboard.

Starring Momo
Python loops ยท Age 9 and up
Sir Oops-a-Lot

Robot Castle

Sir Oops-a-Lot: I must greet 100 guests. I shall type it 100 times!

print("Hello")
print("Hello")
print("Hello")

Momo: Stop! Computers love repeating. Use a loop!

Meet the for loop

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

Momo: Line one says: do this 3 times. The spaces before print show which line repeats.

Sir Oops-a-Lot

Sir Oops-a-Lot: But what is this i? I have only a saucepan.

for i in range(3):
    print(i)
0
1
2

Momo: i is a counter. range(3) starts at 0 and stops before 3.

Your turn, hero!

Sir Oops-a-Lot
Sir Oops-a-Lotโ™ฅโ™ฅโ™ฅ
for i in range(2):
    print("Hi")

How many times does this print Hi?

2. range(2) counts 0 and 1. That is 2 times.

for i in range(3)
print("Hello")
SyntaxError: expected ':'

Momo: Two bugs! The first line needs a colon. The next line needs its spaces.

He tries something new

Sir Oops-a-Lot
Sir Oops-a-Lotโ™ฅโ™ฅโ™ฅ
for i in range(1, 4):
    print(i)

What does this print?

1 2 3. range(1, 4) starts at 1 and stops before 4.

The final battle

Sir Oops-a-Lot
Sir Oops-a-Lotโ™ฅโ™ฅโ™ฅ
total = 0
for i in range(1, 4):
    total = total + i
print(total)

What number comes out?

6. 0 + 1 = 1, then 1 + 2 = 3, then 3 + 3 = 6.

Two lines. One hundred guests.

for i in range(100):
    print("Hello, guest")
Sir Oops-a-Lot

Sir Oops-a-Lot: My saucepan salutes you!

Momo: Now try it yourself!

The End?

Remember

  • A for loop repeats the lines with spaces in front.
  • range(3) gives 0, 1, 2: it stops before 3.
  • The first line ends in a colon.

Next morning a new order arrives: every guest wants a different greeting. His saucepan starts to shake...

A comic book about Python for loops. Learn how range counts, spot the two commonest bugs and save a robot knight from a lot of typing.

Watch this issue

Chat on WhatsApp
Esc

Try