1. Introduction
A while loop repeats a block of code for as long as a given condition remains True. It is best suited for situations where you don't know in advance exactly how many times you need to loop — for example, reading input until the user types 'quit', or repeatedly retrying a network call until it succeeds.
Cricket analogy: A bowler keeps bowling overs in a rain-delayed match while the umpires haven't called it off, not knowing in advance how many overs will be possible — just as a while loop runs while its condition stays True.
Unlike a for loop, which naturally terminates when its iterable is exhausted, a while loop only stops when its condition becomes False, so the programmer is responsible for ensuring that eventually happens.
Cricket analogy: A for loop is like bowling a fixed six-ball over that naturally ends, while a while loop is like a rain delay that only ends when the umpires decide — the scorer, not the format, must ensure it eventually stops.
2. Syntax
while condition:
# runs repeatedly as long as condition is True
statement(s)
else:
# optional: runs only if the loop ended because condition became False
# (not if it ended via 'break')
statement(s)3. Explanation
Before each iteration, Python evaluates condition. If it's True, the block runs and then the condition is checked again; if it's False (even on the very first check), the loop body never runs at all. Something inside the loop body — updating a counter, reading new input, changing a flag — must eventually make the condition False, or the loop will never terminate.
Cricket analogy: Before every ball, the umpire checks whether overs remain; if none remain even before the first ball, no delivery is bowled at all — and something must reduce the overs-remaining count each ball or the innings never ends.
Like the for loop, while also supports an optional else clause that runs only when the loop exits normally (condition became False) rather than via a break.
Cricket analogy: A while loop's else clause is like the post-match presentation that only happens if the game finished its natural course — if it was abandoned early (a break) due to rain, that presentation never runs.
The infinite loop trap: forgetting to update the variable that the condition depends on causes the loop to run forever, e.g., 'i = 0; while i < 5: print(i)' never terminates because i is never incremented. Always double-check that the loop body moves the condition toward False.
Deliberate infinite loops (while True:) are a common and valid pattern for servers, game loops, or menus — as long as they contain a break statement (or return) reachable under some condition to exit.
4. Example
count = 0
total = 0
while count < 5:
total += count
count += 1
print(f"Sum of 0..4 = {total}")
attempts = 0
while True:
attempts += 1
if attempts == 3:
print(f"Succeeded after {attempts} attempts")
break5. Output
Sum of 0..4 = 10
Succeeded after 3 attempts6. Key Takeaways
- while loops repeat as long as their condition evaluates to True.
- The condition is checked before every iteration, including the first — a False condition means the body never runs.
- The loop body must eventually make the condition False, or it becomes an infinite loop.
- while True: combined with an internal break is a common controlled-infinite-loop pattern.
- The optional while-else clause runs only if the loop ends naturally, not via break.
- while loops suit unknown iteration counts; for loops suit known/finite iterables.
Practice what you learned
1. What happens if the condition of a while loop is False from the start?
2. What is the most common cause of an accidental infinite while loop?
3. When does a while loop's else clause execute?
4. What does the following print? i = 5\nwhile i > 0:\n print(i, end=' ')\n i -= 1
5. Which pattern is idiomatic for a loop that should run forever until an internal condition triggers an exit?
Was this page helpful?
You May Also Like
for Loop in Python
Understand how Python's for loop iterates over sequences and iterables like lists, strings, and ranges.
break, continue and pass in Python
Master Python's three loop control statements: break to exit early, continue to skip an iteration, and pass as a no-op placeholder.
range() Function in Python
Learn how Python's built-in range() function generates sequences of numbers efficiently for use in loops.
if-elif-else in Python
Learn how Python's if, elif, and else statements let your program make decisions based on conditions.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics