If the problem with else else is related to raw_input in Python

I am currently following the Zed Shaw Python book, learning the Python Hard Way and learning functions. I decided to follow some of the extra credit exercises that came with the tutorial and added a post about the current IF ELSE thread. This is the code I have below.

print "How much bottles of water do you have?"
water = raw_input("> ")

print "How many pounds of food do you have?" 
food = raw_input("> ")

if food == 1:
    def water_and_food(bottles_of_water, food):
        print "You have %s bottles of water" % bottles_of_water
        print "And %s pound of food" % food

else:
    def water_and_food(bottles_of_water, food):
        print "You have %s bottles of water" % bottles_of_water
        print "And %s pounds of food" % food

water_and_food(water, food)

      

I want to do this. If the user enters they have 1 pound of food, it will display "You have 1 pound of food." If they enter they have 2 pounds of food or more, the display will show "You have 2 pounds of food", the difference in pounds being single or multiple.

However, if I put 1, it still displays "You have 1 pound of food", however, if I directly assign the number to the water and food variables, it works.

+3


source to share


2 answers


The return value raw_input

is a string, but when you check the power value you are using int. However, if food == 1

it can never be True

, so the stream is always plural by default.

You have two options:

if int(food) == 1:

      



The above code will cast food

to integer type, but throws an exception if the user does not enter a number.

if food == '1':

      

The above code checks for the string '1', not an integer (note the surrounding quotes).

+4


source


In Python 2.x, raw_input returns a string. After looking at your code, you can also use input , which returns an integer. I would think this would be the most explicit option using Python2.



Then you can treat food as int throughout your code using% d instead of% s. When you enter a non int, your program throws an exception.

+1


source







All Articles