What else is there in Python?
I would still love to hear your feedback in the comments below. Enjoy!
We all use the
else keyword in Python, usually accompanying an
if x > 0: print 'positive' elif x < 0: print 'negative' else: print 'zero'
but Python has a few other uses to the
else keyword that most people are unfamiliar with.
for .. else
I bet you didn’t know that you can put an
else clause after a
for loop! What does it do? When the items you iterate over are exhausted, the
else clause is executed. When aren’t the items exhausted? When you use a
Using the keyword
else for this clause is kind of silly, as
else doesn’t really describe the behavior here, but this syntactic sugar can be useful if you put a
break somewhere and need to know if it was used. Let’s say we have a computer object and a list of people, and we want each person to use the computer, unless one of them breaks it. At the end, we want to know if the computer was broken or not. Usually, we’d do it like this:
for..else we can do it like this:
while .. else
This has pretty much the same semantics as the
for..else syntax. The main
while body is executed in a loop as long as the condition is satisfied - that far you already know. If the condition is not satisfied, the
else clause is executed. However, a
break statement will break out of the entire
while..else block, so the
else body will not be executed. In a nutshell, it’s the same as the
for loop: the
else will be executed unless you break out of the loop.
try .. except .. else
You got some code in a
try block. You want to catch certain exceptions and handle them, but what if no exceptions were raised? That’s where the
else clause comes in. It’s executed only if no exceptions were caught, and before the
finally clause, if it exists. It’s important to note that exceptions raised by statements in the
else block are not caught by the preceding excepts:
else clause is only executed if
IndexError was not caught. Why is this useful? Well, one would probably put the
person.do_work() bit inside the
try block, but what if do_work raises an
IndexError? In that case, it will be caught by our
except block, which could be catastrophic if we didn’t intend for that. This way, if
do_work raises an
IndexError, it will propagate through the code, as it should.
Well, I haven’t found the
else keyword very useful outside an
if block. My opinion is that with
while loops it should probably be avoided as its behavior is not intuitive. Use it only if it’s more readable than its more verbose alternative. Using
else in a
try statement, on the other hand, is much more intuitive, and is probably a better alternative than catching exceptions you didn’t plan on, or using a variable to store information on whether an exception was raised to be used after the
Follow me on Twitter and Facebook