Loops: for, while, break and continue
Course contents (15 lessons)
- Getting started
- Installing Python 3.13 and running your first script
- Variables and basic data types
- Text, numbers and user input
- Working with strings
- Numbers and arithmetic
- Input and output: talking to the user
- Making decisions and repeating work
- Making decisions with if, elif and else
- Loops: for, while, break and continue
- Collections of data
- Lists and tuples
- Dictionaries and sets
- Functions and modules
- Writing your own functions
- Modules, pip and virtual environments
- Files and errors
- Reading and writing files
- Errors and exceptions
- Final project: expense tracker
- Project: build the expense tracker, part 1
- Project: summaries, search and improvements
Why loops exist
Imagine printing 100 invoice numbers. You could write 100 print lines, but nobody wants to. A loop repeats a block of code. Python has two kinds: for and while.
The for loop
A for loop goes through a sequence of values, one at a time. The most common sequence is made by range().
for i in range(5):
print("Invoice", i)
This prints Invoice 0 up to Invoice 4. range(5) produces 0, 1, 2, 3, 4. It starts at zero and stops before 5, the same rule as string slicing. You can give a start and an end, or a step as well.
for n in range(1, 6): # 1 2 3 4 5
print(n)
for n in range(10, 0, -3): # 10 7 4 1
print(n)
You can also loop over text, and later over lists, directly:
for letter in "Lahore":
print(letter)
The while loop
A while loop repeats as long as a condition is true. Use it when you do not know in advance how many times you need to go around.
import random
secret = random.randint(1, 20)
attempts = 0
print("I am thinking of a number between 1 and 20.")
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret:
print("Too low.")
elif guess > secret:
print("Too high.")
else:
print(f"Correct! You needed {attempts} attempts.")
break
Walking through the guessing game
The random module picks a number. We start a loop with while True, which means "repeat forever". Inside, we ask for a guess, count it, and compare. When the guess is right we print a message and call break, which leaves the loop immediately. Without that break, the game would never end.
break and continue
break exits the loop. continue skips the rest of the current round and jumps to the next one.
for n in range(1, 11):
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop completely
print(n) # prints 1 3 5 7
Accumulating a result
A very common pattern is to start with a total of zero and add to it inside a loop.
total = 0
for price in [250, 400, 175]:
total += price
print(total) # 825
That list syntax is next lesson's topic. The loop pattern is what matters here.
A menu loop
Many small programs show a menu until the user chooses to quit. This is a good use of while.
choice = ""
while choice != "q":
print("1) Say hello 2) Say goodbye q) Quit")
choice = input("Choose: ").strip().lower()
if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")
The else clause on loops
Loops can have an else block that runs if the loop finished without hitting break. It is rarely needed, so just remember that it exists in case you see it in someone else's code.
Common mistakes
- The infinite loop. If a
whilecondition never becomes false and there is nobreak, the program runs forever. Press Ctrl+C in the terminal to stop it. The usual cause is forgetting to change the variable that the condition checks. - Off-by-one errors.
range(1, 10)stops at 9. If you want 10, writerange(1, 11). - Changing a list while looping over it. It gives confusing results. Loop over a copy, or build a new list.
- Forgetting indentation. Only the indented lines repeat. A line at the left margin runs once, after the loop ends.
The first time I wrote a while loop, I forgot to add one to my counter and my laptop fan spun for a minute before I understood why. It is a rite of passage.
Try it yourself
Print a multiplication table for a number the user chooses, from 1 to 10, in the format 7 x 3 = 21. Then extend the guessing game so the player only gets 5 attempts. After the fifth wrong guess, reveal the number. Hint: you can put the attempts check in the while condition.
import random
secret = random.randint(1, 20)
attempts = 0
print("I am thinking of a number between 1 and 20.")
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret:
print("Too low.")
elif guess > secret:
print("Too high.")
else:
print(f"Correct! You needed {attempts} attempts.")
break
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account