For Loop With an Else Clause in Python

For Loop With an Else Clause in Python

Have you ever used a for loop with an else clause in Python? WTH, right? I found out these exist earlier this week when going through some source code. Since it was such a shock I immediately tried to find a use case. Here’s some more detailed documentation. Make sure to search for “4.4” which is the section where you’ll find the info.

So, from my brief research, one way to use a for loop with an else clause in Python is to distinguish if the for loop hits a break statement or finishes without meeting certain criteria. Check out the following.

Never Enters the Else

for i in range(1,3):
    print(i)
# If i ever = 2 then we break and never execute the else.
    if i==2:
            break
else:
    print('Ended naturally')
# This will always execute
print('this still executed')  

This code loops from one to two at which point i = 2 and we enter the if statement. We break and anything after the for loop runs which in this case means we print “this still executed.” If we remove the break, like so then we’ll enter the else statement.

Entering the Else

for i in range(1,3):
    print(i)
else:
    print('Ended naturally')
# This will always execute
print('this still executed')  

So imagine that we’re searching an array for an element. We’ll loop through that array and check if each element is equivalent to ‘foobar’. If we wanted to be notified that nothing was found and continue with the script then we’d have to set a variable that changes when ‘foobar’ is found. We’d then have to add an if statement outside of the loop that checks that variable and notifies us. This can be replaced by tacking on the else statement. More examples to come everybody. Check out this article for some practice manipulating and working with arrays. Happy coding!

Leave a Comment