What else is there in Python?

We all use the else keyword in Python, usually accompanying an if statement:


This is a companion discussion topic for the original entry at http://amir.rachum.com/blog/2012/07/24/what-else-is-there-in-python/

Here's a real example for an else for a for: https://github.com/Peaker/pyun...

for i in xrange(ATTEMPT_COUNT):

...
else:
raise ConnectionFailed("Cannot connect to given host")

That's very cool! Thanks for sharing!

You Almost have it right. consider the code:

for c in computers:
__if c.is_broken: fix(c)
__else: continue
else:
__print "fixed no computers"

The else: clause fires if the end of the for: clause is never reached. This means that the else clause is evaluated if
1. that the input iterable was empty.
2. continue was called every time.
3. break was called after a string of continues.

I think you are not correct. If I execute the following code, then the output is given, although your (exhaustive) list indicates otherwise:

>>> for i in range(10):
... pass
... else:
... print "yay"
...
yay

for-else was cool !

I am still correct. pass is a special case that invalidates the clause, never allowing the end to be "reached", therefore the else: triggers. The rules are complex :<

a = 1 if 9%3 else 4

don't forget it :P