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, 2for 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.breakstops the loop immediately.
A while loop where the condition never becomes false runs forever. If that happens, press the ■ Stop button.
Lesson 5 · Try it
Play with loops
Press Run, then try to:
- Change
range(5)torange(10). Then torange(2, 6). - Add yourself to the crew.
- Remove the line
countdown -= 1and run it. What happens? Press Stop, then put the line back.
Output
Press ▶ Run to see what happens.
Lesson 5 · Exercise
The 7 times table
Print the 7 times table from 1 × 7 to 10 × 7, one line per row, exactly like 3 x 7 = 21.
Output
Press ▶ Run to see what happens.
💡 Need a hint?
Replace pass with: print(f"{i} x 7 = {i * 7}")