Python loops — for and while without beating around the bush
Python loops for and while give your code the ability to repeat itself. Without loops you’d have to write the same instruction a hundred times to do something a hundred times. With loops, three lines. It’s one of the most important concepts in FP1 and also one of the most confusing at first — especially knowing when to use for and when to use while, and understanding break, continue and nested loops.
This article covers everything.
Table of Contents
What are loops?
A loop is a structure that repeats a block of code multiple times. Just like conditionals, indentation and colons are mandatory in Python loops.
There are two types: for and while. The key difference is this:
for → when you know in advance how many times to repeat while → when you don't know and depend on a condition
The for loop
The for in Python iterates over a sequence, a list, a range of numbers, a string — and executes the block once for each element:
# Iterate over a list of grades
grades = [7.5, 8.0, 6.5, 9.0, 5.5]
for grade in grades:
print(grade)
Output:
7.5 8.0 6.5 9.0 5.5
The variable grade takes the value of each element in the list on each iteration. You can call it anything (grade, g, element) but use descriptive names so the code is readable.
The for loop with range()
range() generates a sequence of numbers and is the most common way to use for when you need to repeat something a fixed number of times:
# range(n) generates numbers from 0 to n-1
for i in range(5):
print(i)
# → 0, 1, 2, 3, 4
# range(start, end) generates from start to end-1
for i in range(1, 6):
print(i)
# → 1, 2, 3, 4, 5
# range(start, end, step) with jumps
for i in range(0, 11, 2):
print(i)
# → 0, 2, 4, 6, 8, 10
The detail that confuses most: range(5) goes from 0 to 4, not to 5. The end number is never included. So if you want 1 to 10 you use range(1, 11).
Multiplication table with for:
A classic FP1 use case:
number = 7
print(f"Multiplication table for {number}:")
for i in range(1, 11):
result = number * i
print(f"{number} x {i} = {result}")
Output:
Multiplication table for 7: 7 x 1 = 7 7 x 2 = 14 ... 7 x 10 = 70
The while loop
The while repeats the block while a condition is True. Unlike for, it doesn’t iterate over a sequence, it simply continues until the condition fails:
# Countdown
counter = 5
while counter > 0:
print(counter)
counter -= 1 # IMPORTANT: always update the counter
print("Liftoff!")
Output:
5 4 3 2 1 Liftoff!
The most dangerous while mistake — infinite loops
If you forget to update the condition variable inside the while, the loop never ends and the program freezes:
# DANGER — infinite loop
counter = 5
while counter > 0:
print(counter)
# Missing counter -= 1 → never reaches 0 → infinite loop
If this happens in VS Code press Ctrl + C in the terminal to stop it. The golden rule: whenever you use while, make sure the condition eventually becomes False.
When to use for vs while
This is the question that confuses most. The practical answer:
# USE for — when you know how many times to repeat
for i in range(10): # exactly 10 times
print(i)
for grade in grade_list: # once per grade
print(grade)
# USE while — when you don't know how many times
attempts = 0
while not guessed: # until the player guesses
attempts += 1
...
while answer != "quit": # until the user decides to stop
...
In the number guessing game from the conditionals exercises we used while because we didn’t know how many attempts the player would need. If we’d known it was exactly 5 attempts, we’d have used for.
break — exit the loop early
break interrupts the loop immediately and exits it, even if there are iterations left to do:
# Find the first number divisible by 7
for i in range(1, 100):
if i % 7 == 0:
print(f"First multiple of 7: {i}")
break # found it, exit the loop
Output:
First multiple of 7: 7
Without break the loop would continue to 100 showing all multiples of 7. With break it exits as soon as it finds the first one.
continue — skip one iteration
continue doesn’t exit the loop, it skips to the next element, ignoring the rest of the block in that iteration:
# Show only passing grades
grades = [7.5, 3.0, 8.0, 4.5, 6.5]
for grade in grades:
if grade < 5:
continue # skip this grade and go to the next
print(f"Passed: {grade}")
Output:
Passed: 7.5 Passed: 8.0 Passed: 6.5
Grades 3.0 and 4.5 are skipped, continue makes the loop jump directly to the next iteration without executing the print.
break vs continue — the key difference
# break — exits loop completely
for i in range(10):
if i == 5:
break # stops here, never reaches 6, 7, 8, 9
print(i)
# → 0, 1, 2, 3, 4
# continue — skips that iteration but keeps going
for i in range(10):
if i == 5:
continue # skips 5 but continues with 6, 7, 8, 9
print(i)
# → 0, 1, 2, 3, 4, 6, 7, 8, 9
Nested loops — a loop inside another
Nested loops are two loops where the inner one runs completely for each iteration of the outer one. They’re the hardest loop concept but used a lot in FP1 for tables, matrices and patterns:
# Multiplication tables 1 to 3
for i in range(1, 4): # outer loop: i = 1, 2, 3
for j in range(1, 11): # inner loop: j = 1 to 10
print(f"{i} x {j} = {i*j}")
print() # blank line between tables
For each value of i (1, 2, 3) the inner loop runs through all values of j (1 to 10). Total iterations: 3 × 10 = 30.
Star pattern with nested loops
# Triangle of asterisks
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("*", end="")
print() # newline at the end of each row
Output:
* ** *** **** *****
The end="" in the inner print() prevents the automatic newline — it prints the asterisks in a row on the same line. The outer print() then adds the newline after each complete row.
The accumulator — essential pattern with loops
The accumulator is a pattern that appears in almost every loop exercise, a variable that keeps updating on each iteration:
# Calculate the average of a list of grades
grades = [7.5, 8.0, 6.5, 9.0, 5.5]
total = 0 # accumulator initialised to 0
for grade in grades:
total += grade # total += grade is the same as total = total + grade
average = total / len(grades)
print(f"Average: {average}") # → 7.3
Golden rule: initialise the accumulator before the loop, update it inside, use it after.
Input validation with while — a very useful pattern
One of the most practical uses of while is forcing the user to enter a valid value:
# Ask for a valid grade between 0 and 10
grade = float(input("Enter a grade (0-10): "))
while grade < 0 or grade > 10:
print("Error: grade must be between 0 and 10")
grade = float(input("Enter a valid grade: "))
print(f"Grade recorded: {grade}")
The while keeps asking for the grade until the user enters a value within the valid range. This is what FP1 calls input validation and you’ll see it in many exercises.
Visualise it with Python Tutor
Loops are where pythontutor.com helps most. Paste this and step through it:
grades = [7.5, 8.0, 6.5]
total = 0
for grade in grades:
total += grade
average = total / len(grades)
print(average)
Watch how grade changes on each iteration and how total accumulates. Pay attention to how the arrow jumps back to the top of the for loop after each iteration, that’s the loop repeating. It’s the most visual way to understand what the loop does at each step.
Quick summary
# FOR — known repetitions
for element in sequence: # iterate over list
code_block
for i in range(n): # n times
for i in range(start, end): # start to end-1
for i in range(start, end, step): # with jumps
# WHILE — condition-based
while condition:
code_block
# ALWAYS update the condition variable inside
# WHEN TO USE EACH
# for → know how many times → range, lists, strings
# while → don't know → until player guesses, until valid input
# BREAK — exit loop completely
for i in range(10):
if i == 5:
break
# → 0, 1, 2, 3, 4
# CONTINUE — skip current iteration
for i in range(10):
if i == 5:
continue
# → 0, 1, 2, 3, 4, 6, 7, 8, 9
# NESTED LOOPS
for i in range(rows): # outer
for j in range(cols): # inner — runs completely for each i
code_block
# ACCUMULATOR PATTERN
total = 0 # 1. initialise BEFORE loop
for value in sequence:
total += value # 2. update INSIDE loop
result = total / len(sequence) # 3. use AFTER loop
# INPUT VALIDATION WITH WHILE
value = float(input("Enter value: "))
while value < 0 or value > 100:
print("Invalid — try again")
value = float(input("Enter value: "))
# COMMON ERRORS
# 1. Infinite loop — forgetting to update condition variable → Ctrl+C
# 2. range(n) goes 0 to n-1, not 0 to n
# 3. range(1, 11) to get 1 to 10 (end not included)
# 4. Missing : after for/while → SyntaxError
# 5. Wrong indentation → IndentationError
In the next article we practice Python loops with real programs in VS Code.

2 Comments