Tutorial 8/15 POWER OF REPEATING

Python: For Loops

Master counting and repeating blocks of code with range().

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 using the range() function.

Worked Example

A basic "Counter Clicker" implementation.

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

Active Recall

Predict Logic

We change the start level. What exactly prints?

for x in range(2, 5):
  print(x)
Level 19: Bronze

0 to 9

"Change the range to print numbers 0 to 9. Remember: range(x) stops at x-1."

> bronze_stream_standby
Level 20: Silver

Double It

"We want to print double the number (0, 2, 4, 6...). Fix the print line to calculate i * 2."

> silver_debugger_online
Level 21: Gold

Times Tables

Independent Construction Required

  • Ask for a number using int(input()).
  • Loop through range(1, 11).
  • Calculate ans = num * i.
  • Print results (e.g. 5 x 1 = 5).
> math_module_awaiting_input