Archive
Posts Tagged ‘else’
for / else and try / except / else
June 17, 2016
1 comment
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.
