Code

Light Them All

Imagine lighting 100 lanterns by writing 100 print() lines. No thanks! A loop runs the same block of code again and again.

The for loop

for number in range(3):
    print("Tick", number)

prints:

Tick 0
Tick 1
Tick 2
  • range(3) gives the numbers 0, 1, 2. It starts at 0 and stops before 3.
  • Each time around, the variable number holds the next value.
  • The indented lines belong to the loop. The first line that is not indented runs after the loop has finished.

Want to start somewhere else? Give range two numbers: range(1, 4) gives 1, 2, 3 (start at 1, stop before 4).

Pip tip: The loop variable can have any name. Pick one that says what it holds, like lantern or day.

Assignment

  1. Use a for loop with range to print Lantern 1 is lit! up to Lantern 5 is lit! (five lines, numbers 1 to 5).
  2. After the loop, print All lanterns glow! exactly once.