While loops
A for loop repeats a known number of times — once per item, or once per number in a range. But sometimes you don't know how many repetitions you'll need in advance. You just want to keep going while something is true. That's a while loop.
The while loop
A while loop repeats its block as long as a condition stays True:
Python
Output:
Text
Here's what happens each pass:
- Python checks the condition
count <= 3 - If it's
True, it runs the block - Then it checks again — and stops as soon as the condition is
False
You must change the condition inside the loop
Look closely at count = count + 1. Without it, count would stay 1 forever, the condition would always be True, and the loop would never stop — an infinite loop.
Python
Every while loop needs something inside it that eventually makes the condition False.
Counting down
while loops are natural for counting down:
Python
Output:
Text
for vs while — which to use?
- Use a
forloop when you know how many times to repeat (every item in a list, every number in a range). - Use a
whileloop when you repeat until some condition changes and you don't know the count ahead of time.
Key takeaways
- A
whileloop repeats its block as long as its condition isTrue - Always change something inside the loop so the condition eventually becomes
False - Forgetting to do that creates an infinite loop that never stops
- Reach for
forwhen the count is known,whilewhen it depends on a condition
No comments yet. Add the first comment to start the discussion.