Card 8: For Loops

Module 3: Power of Repeating

1 The Hook

Remember Bart Simpson writing on the chalkboard? He knows exactly how many times to write lines.

When we know the number of repeats, we use a For Loop.
We count with range().

2 Worked Example

A "Counter Clicker".

for i in range(5): # i becomes 0, 1, 2, 3, 4
print(i)

Key Concept: range(5)

Starts at 0.
Stops BEFORE 5.
Output: 0, 1, 2, 3, 4

PREDICT

We change the start number. What prints?

for x in range(2, 5):
  print(x)

Interactive Editor

> _
BRONZE (MODIFY)

🥉 0 to 9

1. Change the range to print numbers 0 to 9.
2. Remember: range(x) stops at x-1. So you need range(10).

> _
SILVER (FIX)

🥈 Double It

We want to print double the number (0, 2, 4, 6...).
But the code just prints 0, 1, 2...
Fix the print line to calculate i * 2.

> _
GOLD (MAKE)

🥇 Times Tables

1. Ask for a number using int(input()).
2. Use a loop range(1, 11).
3. Calculate ans = num * i.
4. Print formatted: print(num, "x", i, "=", ans).

> _