Coding Pirates

Lesson 5

Loops

Computers are great at doing the same thing over and over. A loop is how we ask for that.

for: a known number of times

for i in range(3):
    print(i)   # 0, 1, 2
for name in ["Ada", "Linus"]:
    print(name)

while: as long as something is true

lives = 3
while lives > 0:
    print("still playing")
    lives -= 1
  • The indented lines are the body of the loop. They run every time.
  • range(1, 11) counts from 1 up to 10. The last number is not included.
  • break stops the loop immediately.

A while loop where the condition never becomes false runs forever. If that happens, press the ■ Stop button.

1 / 3