How do Python for and while loops repeat code, and when should each be used?
Use Python for loops with range and while loops with a condition, including accumulators and avoiding infinite loops
A focused answer to the O-Level Computing point on Python loops. Using for with range for a known count, while with a condition for an unknown count, building accumulators, and avoiding infinite loops.
Reviewed by: AI editorial process; not yet individually human-reviewed
Have a quick question? Jump to the Q&A page
Jump to a section
What this dot point is asking
SEAB wants you to use both kinds of Python loop, the for loop with range, and the while loop with a condition, including building accumulators and avoiding loops that never end. The central idea is that a for loop repeats a known number of times while a while loop repeats while a condition holds, and choosing the right one makes a program both correct and clear.
The answer
The for loop with range
A for loop repeats once for each value in a sequence. With range, it repeats a known number of times:
for i in range(5):
print(i) # prints 0, 1, 2, 3, 4
range(5) gives to (five values, starting at ). range(1, 6) gives to : the start is included, the stop is excluded. range(0, 10, 2) counts in steps of .
The while loop
A while loop repeats while a condition is true. Use it when you do not know in advance how many repetitions are needed:
total = 0
while total < 100:
total = total + 25
The condition is tested before each pass. Something inside the loop must move it toward false, or the loop never stops.
Choosing for or while
- Use for when the number of repetitions is known (loop over a range or a list).
- Use while when it depends on a condition (loop until the user enters valid data).
Accumulators and counters
An accumulator is a variable that builds up a result across a loop. Set it before the loop, then update it each pass:
total = 0 # accumulator, set first
for n in range(1, 6):
total = total + n # grows each pass
print(total) # 15
A counter works the same way to count occurrences.
Avoiding infinite loops
A while loop runs forever if its condition never becomes false. Make sure the body changes a value used in the condition (read new input, increase a counter, or shrink a value) so the loop can end.
Examples in context
Example 1. Summing a shopping basket. A program loops with for item in prices over a list of prices, adding each to a total accumulator. Because the number of items is known from the list, a for loop is the natural, clear choice.
Example 2. A login attempt limit. A while loop keeps asking for a password while it is wrong and attempts remain, increasing an attempts counter each pass. The counter ensures the loop ends even if the user never gets it right, avoiding an infinite loop.
Try this
Q1. State what range(0, 10) produces. [2 marks]
- Cue. The numbers to (start included, stop excluded).
Q2. Write a for loop that prints the numbers to . [2 marks]
- Cue.
for i in range(1, 6): print(i).
Q3. Explain one way to stop a while loop running forever. [2 marks]
- Cue. Make the loop body change a value used in the condition (such as reading new input or increasing a counter) so the condition can become false.
Exam-style practice questions
Practice questions written in the style of SEAB exam questions on this dot point, with worked answer explainers. The year tag is the paper they imitate, not the source.
Original5 marksWrite a Python program that uses a for loop to add the numbers from to and print the total. State what `range(1, 101)` produces and why.Show worked answer →
Use an accumulator that starts at and grows inside the loop:
total = 0
for n in range(1, 101):
total = total + n
print(total)
range(1, 101) produces the numbers . The start is included but the stop is excluded, which is why you write to reach . The total printed is .
Markers reward initialising total to , a for loop over range(1, 101), adding each n to the total, and noting the stop value is excluded.
Original5 marksA program should keep asking the user to guess a secret number () until they get it right, then print 'Correct'. (a) Write the program using a while loop. (b) Explain how your loop avoids running forever.Show worked answer →
(a) Read a first guess, then loop while it is wrong:
guess = int(input("Guess: "))
while guess != 7:
guess = int(input("Try again: "))
print("Correct")
(b) The loop avoids running forever because the body reads a new guess each pass, so the condition guess != 7 can become false. As soon as the user enters , the condition is false and the loop ends. A loop that never changed guess inside would loop forever.
Markers reward an initial input, a while condition that repeats while wrong, reading a new value inside the loop, and explaining that updating the variable lets the loop end.
Related dot points
- Declare and use Python variables, identify the core data types (int, float, str, bool), and convert between them
A focused answer to the O-Level Computing point on Python variables. Assigning variables, the core data types int, float, str and bool, reading input as a string, and converting between types with int(), float() and str().
- Use Python selection with if, elif and else, build conditions with comparison and logical operators, and order branches correctly
A focused answer to the O-Level Computing point on Python selection. Using if, elif and else, comparison operators, combining conditions with and, or and not, and ordering branches so each value falls into the right one.
- Define and call Python functions with parameters and return values, and explain the benefits of using functions
A focused answer to the O-Level Computing point on Python functions. Defining functions with def, passing parameters, returning values, the difference between a parameter and an argument, and why functions make programs reusable.
- Use Python lists and strings, including indexing, length, looping over items, and basic operations like append and slicing
A focused answer to the O-Level Computing point on Python lists and strings. Creating lists, zero-based indexing, finding length with len(), looping over items, appending, and basic string operations and slicing.
- Describe and trace the bubble sort, explaining how repeated passes of comparisons and swaps sort a list
A focused answer to the O-Level Computing point on sorting. How bubble sort compares neighbouring items and swaps them, how each pass moves the largest value to the end, and tracing the algorithm by hand.