Discover a simple trick that makes your loops smarter and your code cleaner!
Why While–else behavior in Python? - Purpose & Use Cases
Imagine you want to check a list of numbers to find if any number is negative. You write a loop to check each number, but you also want to do something special if no negative number is found.
Without the while-else behavior, you have to use extra flags or complicated code to remember if you found a negative number or not. This makes your code longer and harder to read, and you might forget to update the flag correctly, causing bugs.
The while-else behavior lets you run a block of code after the loop finishes normally, but skips it if the loop ends early with a break. This means you can easily handle the case when no negative number is found without extra flags or complicated checks.
i = 0 found = False while i < len(numbers): if numbers[i] < 0: found = True break i += 1 if not found: print('No negatives found')
i = 0 while i < len(numbers): if numbers[i] < 0: break i += 1 else: print('No negatives found')
This behavior makes your loops clearer and your code easier to understand by directly linking the loop's normal completion to a special action.
Checking user input repeatedly until a valid input is found, and if the user never enters a valid input, showing a message after the loop ends.
While-else runs the else block only if the loop did not break early.
It helps avoid extra flags or complicated checks after loops.
It makes your code cleaner and easier to read.