# while statements

kyosohma at gmail.com kyosohma at gmail.com
Tue Oct 16 16:09:20 CEST 2007

```On Oct 16, 8:28 am, Shawn Minisall <trekker... at comcast.net> wrote:
> I just learned about while statements and get why you place them around
> inputs for validation, but I'm a little lost on exactly where to place
> it with what condition in this program where the number of fat grams
> exceeds the total number of calories so that it loops back and asks you
> the two questions again instead of just saying The calories or fat grams
> were incorrectly entered.  Any idea's?
>
> thx
>
> while cal <=0:
>     #Prompt for calories
>         cal = input("Please enter the number of calories in your food: ")
>         if cal <=0:
>             print "Error.  The number of calories must be positive."
>
>     #Prompt for fat
>         fat = input("Please enter the number of fat grams in your food: ")
>         if fat <=0:
>             print "Error.  The number of fat grams must be positive."
>
>     #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
>
>     #evaluate input
>     if calfat > cal:
>         print "The calories or fat grams were incorrectly entered."
>
>     elif calcent > 0 and calfat < cal:
>
>         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

I would think using 2 while loops would be easiest.

<code>
# untested

cal=0
calfat = 1
while calfat > cal:
while cal<=0:
#Prompt for calories
cal = int(raw_input("Please enter the number of calories
in your food: "))
if cal <=0:
print "Error.  The number of calories must be
positive."
fat=0
while fat <=0:
#Prompt for fat
fat = int(raw_input("Please enter the number of fat grams in