if then elif

Larry Bates larry.bates at websafe.com
Wed Oct 10 17:03:07 EDT 2007


Shawn Minisall wrote:
> I just learned about if, then elif statements and wrote this program.  
> The problem is, it's displaying all of the possibilities even after you 
> enter a 0, or if the fat grams are more then the total number of 
> calories , that is supposed to stop the program instead of continuing on 
> with the print statements that don't apply.  Any idea's?  thanks
> 
>    #Prompt for calories
>    cal = input("Please enter the number of calories in your food: ")
> 
>    #Prompt for fat
>    fat = input("Please enter the number of fat grams in your food: ")
> 
>    #Input validation
>    if cal or fat <= 0:
>       #Display message
>        print "Error.  The number of calories and/or fat grams must be 
> positive"
>        print
> 
>    else:
>    #Calculate calories from fat
>        calfat = float(fat) * 9
>          #Calculate number of calories from fat
>        caldel = calfat / cal
> 
>    #change calcent decimal to percentage
>        calcent = caldel * 100
> 
>    if calfat > cal:
>        print "The calories or fat grams were incorrectly entered."
> 
>    else:
>    #evaluate input
>        if caldel <= .3:
>            print "Your food is low in fat."
>        elif caldel >= .3:
>            print "Your food is high in fat."
> 
>    #Display percentage of calories from fat
>        print "The percentage of calories from fat in your food is %", 
> calcent
> 
> Here's an example of the output...
> 
> Please enter the number of calories in your food: 50
> Please enter the number of fat grams in your food: 30
> Error.  The number of calories and/or fat grams must be positive
> 
> Your food is low in fat.
> The percentage of calories from fat in your food is % 0.0
> 
> It was supposed to print The calories or fat grams were incorrectly 
> entered since the calories from fat was greater then the total number of 
> calories.

Boolean problem:


if cal or fat <= 0

That may be the way you say it or "think" it but it won't work.

'cal or fat' is evaluated first.  Since they both have values this ALWAYS 
evaluates to 1 which is NEVER less than or equal to 0.

You are looking for

if (cal <= 0) or (fat <=0):

(Note: Parenthesis not required, but it may help you understand precedence of 
evaluation.  Also read here:

http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.html

-Larry




More information about the Python-list mailing list