What else is there in Python?

This post is a few years old now, so some details (or my opinions) might be out of date.
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 statement:

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 break statement.

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:

broken = False 
for person in people:
    person.use(computer)     
    if computer.is_broken:         
        broken = True         
        break 
if not broken:     
    print 'The computer is fine!'

With for..else we can do it like this:

for person in people:     
    person.use(computer)     
    if computer.is_broken:         
        break 
else:     
    print 'The computer is fine!' 

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.

while usage < 10 and person.want_to_play:     
    person.use(computer)     
    if computer.broken:         
        break 
else:     
    print 'The computer is fine!' 

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:

def get_person(people):
    try:         
        person = people[3]     
    except IndexError:         
        person = None     
    else:         
        person.do_work()     
    return person 

The 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.

Conclusion

Well, I haven’t found the else keyword very useful outside an if block. My opinion is that with for and 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 try..except block.

Discuss this post at the comment section below.
Follow me on Twitter and Facebook

Similar Posts