
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 numbers0, 1, 2. It starts at 0 and stops before 3.- Each time around, the variable
numberholds 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
lanternorday.
Assignment
- Use a
forloop withrangeto printLantern 1 is lit!up toLantern 5 is lit!(five lines, numbers 1 to 5). - After the loop, print
All lanterns glow!exactly once.
- Use a
forloop withrangeto printLantern 1 is lit!up toLantern 5 is lit!(five lines, numbers 1 to 5). - After the loop, print
All lanterns glow!exactly once.
main.py Python sleeping
Press Run to try your code, then Check to test it.