Learn
02.3 | FOR LOOPS AND RANGE
01 | REPEAT A TASK WITHOUT COPYING IT
Suppose a program needs to print a reminder five times. Five copied print statements would work, but changing the repetition count would mean editing the source repeatedly.
A loop repeats an instruction group. That group is the loop body. One execution of the body is an iteration. These terms describe what repeats and how many times it runs.
Python for takes successive values from an iterable, a source of values that can be visited in order. In this lesson, range supplies a sequence of integers so we can control counted repetition.
for count in range(5):
print("Remember to save your work")02 | READ THE LOOP HEADER
for count in range(5): means take each value supplied by range(5), assign that value to count, and execute the indented body. The colon introduces that body, just as it did for if.
range(5) supplies 0, 1, 2, 3 and 4. There are five values, so the body runs five times. The loop name count is a variable, not a fixed keyword; choose a name that explains its role.
After the final value, execution continues with the next statement outside the body. Python does not need NEXT or ENDFOR.
for count in range(5):
print("Count:", count)
print("Finished")EXPECTED OUTPUT
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4 Finished
03 | RANGE EXCLUDES THE STOP
range(start, stop) begins at start and supplies increasing integers before stop. The stop is excluded. range(1, 6) therefore supplies 1, 2, 3, 4 and 5.
Do not transfer the inclusive endpoint rule of Cambridge pseudocode FOR directly to Python range. They use different notation and endpoint conventions.
For a display numbered one to five, range(1, 6) is clearer than changing the counter manually. To repeat n times from zero, range(n) is a common choice.
for number in range(1, 6):
print(number)EXPECTED OUTPUT
1 2 3 4 5
04 | A STEP CHANGES THE SEQUENCE
range(start, stop, step) changes by step between supplied values. range(1, 8, 2) supplies 1, 3, 5 and 7. It does not include eight because stop is excluded and the step would skip it anyway.
A negative step counts down. range(5, 0, -1) supplies 5, 4, 3, 2 and 1. The stop still remains excluded.
Step cannot be zero: range raises ValueError. With a positive step but start already at or above stop, the sequence is empty. A negative step needs a descending route, or it can also be empty.
for number in range(5, 0, -1):
print(number)
print("Launch!")EXPECTED OUTPUT
5 4 3 2 1 Launch!
05 | ZERO ITERATIONS CAN BE CORRECT
range(5, 3) is empty with its default positive step. The body does not execute. A statement after the loop still runs normally.
Likewise, range(0) supplies no values. This can be useful when the repetition count is zero, but it exposes a mistake if you intended a countdown.
Check the start, excluded stop and direction together. Do not solve every empty loop by adding one to an arbitrary number.
for number in range(5, 3):
print(number)
print("Loop complete")EXPECTED OUTPUT
Loop complete
06 | THE COUNTER IS SUPPLIED BY FOR
The next iteration gets the next value from the iterable. Changing number inside the body does not alter the range sequence itself; the next iteration will assign its next supplied value.
For a successful non-empty loop that does not reassign the loop name later, Python leaves that name referring to its last assigned value. If the loop is empty, it supplies no new assignment; an earlier value may remain, or a previously undefined name remains undefined.
Avoid relying on a counter after the loop when the required result can be calculated or stored clearly. This keeps the program safe for empty sequences.
07 | BUILD A TOTAL THAT KEEPS EARLIER VALUES
A running total begins at zero before the loop. Each iteration adds the next value to the total so far. For values one through four, total becomes 1, 3, 6 and 10.
total = total + number keeps the earlier accumulated amount and adds the current number. total = number would discard earlier contributions. Resetting total to zero inside each iteration would do the same damage.
The output after the body gives the final total. An output inside the body shows each partial total instead, which can be useful for tracing.
total = 0
for number in range(1, 5):
total = total + number
print("Final total:", total)EXPECTED OUTPUT
Final total: 10
08 | PRINT A MULTIPLICATION TABLE
A for loop can combine a changing counter with a fixed user choice. Each multiplier generates a different product while the chosen base stays the same.
The loop executes ten times because range(1, 11) supplies one through ten. Its body calculates a product and prints a labelled line. Input happens once before the loop, not once per row.
base = int(input("Multiplication table number: "))
for multiplier in range(1, 11):
product = base * multiplier
print(f"{base} x {multiplier} = {product}")09 | STEP THROUGH A RANGE AND ITS TOTAL
Choose a start, excluded stop and non-zero step. The constrained demo lists the supplied values, then reveals the running total one iteration at a time. It does not execute arbitrary Python.
10 | COMBINE A LOOP WITH A DECISION
The body can contain an if. The loop visits every supplied value, but the condition decides whether to add that value. For numbers one through six, the even numbers are two, four and six, giving a total of twelve.
Modulo checks divisibility: number % 2 == 0 means no remainder after division by two. The deeper indentation places the addition inside if, which is itself inside for.
total = 0
for number in range(1, 7):
if number % 2 == 0:
total += number
print(total)EXPECTED OUTPUT
12
11 | YOUR COUNTED REPETITION CHALLENGE
Write a countdown from a positive input to one, followed by a launch message. Then write a separate program totalling the integers from one through an input limit.
Test a limit of one and a limit of four. For totalling, expected results are one and ten. Test zero if your stated requirement permits it and explain the empty range.
Extension: accept three numeric readings with a loop and output their total and mean. Input belongs inside the body; initialising total belongs before it. Explain why those locations differ.
PUT YOUR SKILLS TO WORK
Use the Section 2 challenges to practise these ideas independently. Work in your Python editor, predict results and keep a short test record.
Section 2 challenges Python course navigation