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.

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 comment

Design a site like this with WordPress.com
Get started