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

jim jim at well.com
Tue Jun 28 17:44:07 UTC 2011



    consider the concept of "default", some action 
taken in the absence of other direction. 
    when you think out your problem, you should 
consider whether you should have some default 
action. 
    If so, you use the else keyword. 
    If not, your default action is to do nothing, 
and in that case you do not use the else keyword. 




On Tue, 2011-06-28 at 10:19 -0700, akkana at shallowsky.com wrote:
> 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.
> 
> 	...Akkana
> _______________________________________________
> Courses mailing list
> Courses at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/courses
> 




More information about the Courses mailing list