Imagine your teacher asked you to write 'I will not eat chocolate in class' 500 times on the whiteboard. Your hand would ache! In Python, we can make the computer do 500 repetitive tasks in less than a blink of an eye using loops.
Words to own
- Loop
- Code that repeats instead of being written out again and again.
- For loop
- A loop that repeats a set number of times, or once for each item in a collection.
- range()
- A built-in Python function that builds a sequence of numbers for a for loop.
- While loop
- A loop that keeps repeating while a condition stays True.
- Infinite loop
- A while loop whose condition never becomes False, so it never stops running.
- Iteration
- A single round of repeating the code inside a loop.
Why Do We Loop?
Computers never get bored, tired, or complain. If you ask a computer to print a message ten thousand times, it does it instantly.
In programming, writing the same line of code over and over is a bad habit. Instead, we use loops to write the instructions once and tell Python how many times to repeat them.
| Point | For Loop | While Loop |
|---|---|---|
| When to use | When you know the exact number of repeats in advance. | When the number of repeats depends on something changing while running. |
| Control mechanism | Uses a counter or goes through a collection like range(). | Uses a logical condition (True/False) to decide. |
| Risk of crash | Extremely low risk. It stops automatically when it finishes the range. | High risk of infinite loops if you forget to update the condition variable. |
| Example scenario | Printing the 7 times table up to 12. | Asking a user to type their password until they get it right. |
For Loops: Counting with range()
A for loop repeats a fixed number of times. We use a helper function called range() to tell it how many times to run.
When we write 'for i in range(5):', Python runs the code inside five times. The variable 'i' acts as a counter, starting at 0 and stopping before it hits 5. So it counts 0, 1, 2, 3, then 4.
for i in range(5):
print("This is loop number", i)While Loops: Running Until Things Change
Sometimes you do not know how many times you need to repeat in advance. For example, in a game, you want to keep playing until the player runs out of lives.
A while loop repeats as long as a specific condition stays True. Every time the loop finishes one round, Python checks the condition again. If it is still True, it runs again. If it becomes False, it skips past the loop.
lives = 3
while lives > 0:
print("Playing game... Lives remaining:", lives)
lives = lives - 1
print("Game Over!")When Loops Go Wild: Infinite Loops
An infinite loop is a loop that never stops because its condition never becomes False. It will run forever, making your computer fan spin fast and freezing your program.
To avoid this, always make sure that something inside your while loop changes the variables in the condition so that it will eventually turn False.
Your turn — run real Python
The Seven Times Table
Change the starter code to print the 7 times table all the way up to 7 x 12. Currently, it only prints the 3 times table up to 3 x 5.
Bug hunt
What is wrong with this code?
count = 1
while count <= 5:
print("This is count:", count)Myth-busting corner
Mythrange(5) counts up to 5.
Truthrange(5) starts at 0 and counts up to 4. It produces 5 numbers in total (0, 1, 2, 3, 4), but never reaches the end number itself.
MythWhile loops are always better because they can do anything.
TruthFor loops are cleaner and safer when you know the number of loops. While loops should only be used when the end point is truly unpredictable.
Exam answer that scores full marks
When would you use a while loop instead of a for loop?
Use a for loop when you know how many repeats you need, such as printing a times table 12 times. Use a while loop when the number of repeats depends on something that happens while the program runs, such as asking the user again and again until they type a valid answer. A while loop must contain something that eventually makes the condition False, or it becomes an infinite loop.
Why it scores
- Clearly defines the specific purpose of both loop types.
- Uses concrete examples (times table vs password entry) to support the explanation.
- Identifies the crucial requirement of while loops to avoid infinite loops.