A while loop repeats a block of code as long as a condition is true. You can think of it as: “Keep doing this until the condition is no longer met.”
While loops are useful when you don’t know in advance how many times something should repeat, but you want it to continue until a certain situation changes.
The basic idea
count = 1
while count <= 5:
print("This is loop number", count)
count += 1
This prints five lines, increasing count each time, until the condition count <= 5 becomes false.
Why while loops are useful
Unlike a for loop (which repeats a set number of times), a while loop keeps going until the condition fails. This makes it perfect for things like:
- Waiting for the correct user input
- Running a game until the player quits
- Repeating a task until a result is found
Useful things to try
- Write a loop that prints numbers from 1 to 10 using a counter.
- Make a guessing game: loop until the user types the correct word.
- Create a loop that counts down from 5 to 1 and then prints “Blast off!”.
Summary
- A while loop repeats as long as its condition is true.
- It is ideal when the number of repetitions is not known in advance.
- Always make sure the condition will eventually become false, otherwise the loop runs forever!





