Home > python > for / else and try / except / else

for / else and try / except / else

Problem
What is that “else” in a for loop? And that “else” in an exception handler?

Solution
They can be confusing but in this thread I found a perfect way to remember what they mean. Asdayasman suggests that we should always annotate these “else” branches:

for _ in []:
    ...
else:  # nobreak
    ...

try:
    ...
except:
    ...
else:  # noexcept
    ...

To be honest, IMO it is best to avoid for / else completely.

Advertisements
Categories: python Tags: , , ,
  1. June 20, 2016 at 09:45

    I try to avoid the use of use of for / else as well.

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: