Menu Home

Thing people on the Internet have an opinion about: Python’s loop/else

Before I even tell you about today’s Python tip, I’ll warn you that there are a lot of opinions on the Internet about whether it’s even a good idea to use, so be sure to pick a side and dig in! Anyway, YMMV, and if you’re writing code that needs to be maintained by a lot of other people who may be confused by the syntax, take that into account. Onwards!

I’m assuming you’re familiar with Python’s for-loops and while-loops. Sometimes you’ll write a loop that has a conditional inside that causes the loop to break. Let’s review the break statement: it’s used to terminate a loop early and picks up execution at the next line after the end of the loop.

For example, if you have a for-loop that’s going from counter = [0,10), you can have a break statement that will cause you to leave the loop at, say, counter = 5. Or if you have a while-loop, you can break without ever failing the conditional (e.g. if you have while (flag = TRUE), you can break even with flag never flipping to FALSE).

How can you know if the loop exited ‘normally’ or if it hit a break

Option 1 is to create a variable to track this. Initialize it before the loop to false, and flip it to true if your conditional is met inside the loop and you’re about to hit a break statement. Then after the loop, check whether the break flip was switched by using another conditional and execute whatever other code you want.

breakFlag = FALSE

for item in iterable:
    if (condition):
        breakFlag = TRUE
        break

if (breakFlag = FALSE):
    ... code block ...

That’s fine, but does require you to keep track of another flag variable. It also puts distance between the loop and the second conditional that checks the flag, adding the potential for error and complexity as the code is maintained. Can you use something built in to Python to avoid that?

Yes, that’s option 2: using a loop/else construct.

for item in iterable:
    if (condition):
        break
else # i.e. no break 
    ... code block, e.g. raise an exception ... 

Admittedly, the choice to use else as the keyword adds to the confusion. One very common way people address the potential for confusion is to add a comment on the else such as “no break,” to help those reading your code who may not be familiar with the paradigm.

Happy coding!

Categories: Uncategorized

Lara K

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: