[Courses] [python] Lesson 2: should you always add "else" ?

akkana at shallowsky.com akkana at shallowsky.com
Tue Jun 28 17:19:56 UTC 2011

Tino (and I think some other people) had read that it's a good idea
always to have an else clause when you're doing if-elif. Generally,
yes, it is a good idea ... at least if the else could do something
useful, like error checking. But don't just shoehorn an "else" in if
it doesn't make sense.

For example: in "print numbers as words" problem, several people did
things like:

for i in range(1, 6) :
    if i == 1 :
        print "one"
    elif i == 2 :
        print "two"
    [ ... similar code for 3 through 5 ]
    else :
        print "What's going on? i was", i

That's a great use of an else. In this case, you're pretty sure that
you shouldn't ever get anything that's not 1 through 5, but if you
ever did, it means there might be a bug in your program and you'd want
to know about it.

Sometimes you'll have programs where you really only care about a few
values, and for the rest, you really don't need to do anything. It's
fine not to have an else in that case. So don't feel like you have to
put one there every time.

I also saw some solutions like:

for i in range(1, 6) :
    if i == 1 :
        print "one"
    elif i == 2 :
        print "two"
    [ ... similar code for 3 through 4 ]
    else :
        print "five"

That's fine as a solution for this exercise, since in this case you
know i will always be between 1 and 5. But in a real program, it
wouldn't be quite as good.  What if you wanted to change the program
later to add zero and six through nine?  Then it would be weird to
have the else be for 5 rather than 9 or 0, so you'd probably end up
changing that part of the program.

Also, if someone else was reading the program for the first time and
trying to figure out how it worked, they'd have to stop and think
"Wait, why does it always print five if it's not 1 through 4?" Then
they'd have to go back and look at where the number comes from (the
for i in range) before that line would make sense. It's a little
easier to read if you treat all the numbers the same way, each with
its own "if" instead of having one be different.


More information about the Courses mailing list