PROGRAMMING, PYTHON

Did you know that in Python for
and while
loops have an else
clause? Why do we have it? What does it mean? How does it work? Where can you use it in your day to day work? Come, let us explore!
Understand For-Else and While-Else
For many of us, the term `elsecreates confusion, because
elsein an
if-elsestatement makes sense but an
elsefor a loop? Weird! For a moment, stop trying to make sense of the word
else`. Just think that Python is offering you an additional feature with its loops. Let us see how it works.
Syntax
The for
loop with optional else
clause:
for variable_name in iterable:
#stmts in the loop
.
.
.
else:
#stmts in else clause
.
.
.
The while
loop with optional else
clause:
while condition:
#stmts in the loop
.
.
.
else:
#stmts in else clause
.
.
.
- The
else
clause will not be executed if the loop gets terminated by abreak
statement. - If a loop does not hit a
break
statement, then theelse
clause will be executed once after the loop has completed all its iterations (meaning, after the loop has completed normally).

Raymond Hettinger, a Python pioneer mentioned in one of his presentations to always comment
#no break
next to theelse
clause of a loop in Python. If loop’selse
was termed as nobreak instead, then there would have been no confusion.
Simplified Real-World Examples
Are you thinking, what’s the point? How can this be of any use to me? Come, let’s explore some interesting Applications which can be useful for you.
A) Search
Traditional Approach
Traditionally, flags were used in search programs to keep a tab on whether a value was found or not. If you had to search for more values, then it increased the complexity of maintaining many flag variables.
#*************************Traditionally*************************
#set flag = 0
#loop the items in the data
#if the item was found in the loop then set flag = 1
#display search result by verifying the flag value
#***************************************************************
Better Approach in Python
But with Python, you could easily write a search program without having to use any flags. You could instead use a break
statement and the loop’s else
clause, to get the job done easily. A simple search Example is given below.
B) To Check Limits
Traditional Approach
Traditionally, a flag variable was used to check if the data has breached given limits.
#*************************Traditionally*************************
#set flag = 1
#loop the items in the data
#if any item breaches the given limits then set flag = 0
#display the validation result by verifying the flag value
#***************************************************************
Better Approach in Python
But with Python, you could easily validate this using break
statement and loop’s else
clause. No flags are needed. Take a look at the example below.
C) Nested Loops
Traditional Approach
Older languages had GOTO
statements to alter the line of execution in a program. This approach was tricky and hence had more chance of committing a human error. If you had nested loops and a couple of GOTO
statements in them, then it only added more complexity and risk.
#************************Older Languages************************
#outer_label: outer loop
# inner loop
# if a condition was met, GOTO outer_label
#***************************************************************
Better Approach in Python
But in Python, there is no GOTO
statement and that’s a good thing. In fact, this is one of the reasons why Python introduced break
and loop’s else
statements – to replace the GOTO
statement. Hence, making it easier and safer for programmers to use them.
- When we have to manage nested loops, we can easily break from an inner loop and get the line of execution to the outer loop using a
break
statement. - And if you need to check whether the inner loop completed executing all its iterations normally without hitting a break statement, you could use the loop’s
else
clause.
Keep in mind that in Python, you cannot break multiple nested loops using a single
break
statement. Onebreak
statement can only break the one loop which contains it.
To understand this clearly, take a look at the example below.
D) Use with Exception Handling
If you want to terminate a loop if it raises an exception, then you could use a break
statement in the except
block. Further, if you want to execute some statements only if the loop has completed normally (meaning, completed all its iterations without hitting a break) then you could write those statements inside the loop’s else
clause. Go through the below example to understand it better.
Takeaway:
- The
else
clause of a loop (for
/while
) gets executed only if the loop has completed its execution fully without hitting a break statement (in other words, loop has completed normally). - The statements inside the loop’s else clause will get executed once after the loop has completed normally.
- How to keep confusion away? Think of the loop’s else clause as no-break. Always comment
#no break
next to theelse
clause of a loop, a best practice for better code readability suggested by Raymond Hettinger, a Python pioneer.
4. Where can you use it?
- To search (instead of using flags, use
break
and loop’selse
). - To check limits/boundaries (instead of using flags, use
break
and loop’selse
). - To manage nested loops (when you need to take action based on whether the inner loop got executed normally or hit a break statement).
- You could use it along with exception handling (when you need to
break
on exception and execute certain statements only if the loop was completed normally).
5. A Word of Caution: Always verify the indentation of the loop’s else
clause, to check if it is properly aligned (indented) with the loop keyword(for
/while
). By mistake, if a loop’s else
clause gets aligned (indented) with an if
statement, then the code will break.
With this, I hope that you are confident about for-else and while-else in Python. You also got familiar with a few of its applications. Repeat with me "No More Confusion :)"!
Please comment below if you have come across any other applications (uses) of for-else and while-else.
Originally published at Pythonsimplified on 12-Feb-2021.
To read more interesting articles on Python and Data Science, subscribe to my blog pythonsimplified.com. You can also reach me on LinkedIn.