Else With While!
else with while! Yes, I just learned about it yesterday.
Coming from a Java background, I was surprised — but yes, it exists in Python!
While working on the LeetCode problem Asteroid Collision (yeah, basic stuff for some of you), I found an optimized solution that uses else with while.
So, let’s explore it a little more and dive into its use cases.
The while-else structure in Python extends the standard while loop functionality. The else block of while-else executes only when the while loop finishes naturally without encountering a break.
i = 0
while i < 5:
print(i)
i += 1
else:
print("Loop finished without a break")output of this code will be:
0
1
2
3
4
Loop finished without a breakHowever, this code will not execute the else part.
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
else:
print("Loop finished without a break")Output of this code is:
0
1
2
3It is useful in which scenario?
Get Akanksha katoch’s stories in your inbox
Join Medium for free to get updates from this writer.
1. Check if a loop completed fully (without hitting a `break`).
2. Execute cleanup code only if no early exit occurred.
3. Handle search/failure cases cleanly.
Real problems and scenarios I’ll think to use while-else loop next time.
- Searching for an item in a list.
Problem: Find if a number exists in a list. If not, return the default value.
Code example without while-else:
found = False
for num in numbers:
if num == target:
found = True
break
if not found:
print("Not found")Code with while-else:
while numbers:
if numbers.pop() == target:
print("Found!")
break
else:
print("Not found")More examples are the retry mechanism, validation, or search.
It leads to cleaner code — that’s all. It doesn’t optimize performance, but clearly distinguishes between loop success and failure to increase the readability.
I hope I remember this when writing code next time.
See you in the next post about a new topic I learned.








