Subject: Re: [Edu-sig] problem with IF

Lloyd Hugh Allen lha2 at columbia.edu
Fri Jul 23 13:17:57 CEST 2004


Two things. First, you want to use elif. Second, you want to go from 
most specific to least specific (or else to use a pair of bounds). I'm 
going to use a different example, because it would take too long to talk 
about eight cases. I think that you might have started with a nested if, 
but that will barely fit on your screen after eight indentations...

Let's say that one is one, two is a couple, and three is many. I want to 
know how many widgets I have, and I'll start with what you have and see 
what happens.

widget = 5

if widget >= 1:
     print "I have one widget"
if widget >= 2:
     print "I have a couple of widgets"
if widget >= 3:
     print "I have many widgets"

and then the program dutifully prints

I have one widget
I have a couple of widgets
I have many widgets

This is a problem. We only want one case. To guarantee mutual 
exclusivity, we use elif, which is an abbreviation for else if.

widget = 5

if widget >= 1:
     print "I have one widget"
elif widget >=2:
     print "I have a couple of widgets"
elif widget >=3:
     print "I have many widgets"

except that now we get the unfortunate output

I have one widget

when we know in our heads that we have many widgets. This can be fixed 
by reversing the order of the cases--the condition widget >= 1 will be 
satisfied for every single value of widget that also >= 3, so we have to 
start with the widget >=3.

widget = 5

if widget >= 3:
     print "I have many widgets"
elif widget >=2:
     print "I have a couple of widgets"
elif widget >=1:
     print "I have one widget"

now the program hits the case that widget >= 3, sees that this is true, 
displays I have many widgets, and then STOPS. Which is good. It's also 
good to include an else at the end so that the program notifies you that 
an unexpected value (say, zero or a negative number) was encountered.

widget = -5

if widget >= 3:
     print "I have many widgets"
elif widget >= 2:
     print "I have a couple of widgets"
elif widget >= 1:
     print "I have one widget"
else:
     print "The value of widget is unexpected: " + `widget`

the backquotes around the widget allow `widget` to act as a string; you 
can't otherwise concatenate a string with a numeric value, and I sense 
that I shouldn't talk about string formatting yet. And I'll ignore the 
possibility of a real-valued number of widgets--what would you do with 
1.5 widgets anyway?

Oh, and my email spell-checker went and turned all the "elif"s into 
"elf"s, so if I left an elf in there, please turn him back into an elif. 
Sorry.


On an unrelated note: looking forward to Vancouver...looks like a good 
schedule.

-Lloyd


More information about the Edu-sig mailing list