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.
Key Concept: range(5)
Starts at 0.
Stops BEFORE 5.
Output: 0, 1, 2, 3, 4
Predict Logic
We change the start level. What exactly prints?
print(x)
0 to 9
"Change the range to print numbers 0 to 9. Remember: range(x) stops at x-1."
Double It
"We want to print double the number (0, 2, 4, 6...). Fix the print line to calculate i * 2."
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).