简体   繁体   中英

If…else statement issue with raw_input on Python

I'm currently following Zed Shaw's book on Python, Learn Python the Hard Way and I'm learning about functions. I decided to follow some of the extra credit exercises that went along with the lesson and added an IF ELSE flow statement. 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)

What I want to do is this. If the user inputs they have 1 pound of food, it will display "You have 1 pound of food" If they input they have 2 pounds of food or more, it will display "You have 2 pounds of food," the difference of pound being singular or plural.

However, if I put 1, it will still display "You have 1 pounds of food," however if I directly assign a number to the variables water and food, it will work.

The return value of raw_input is a string, but when you check the value of food, you are using an int. As it is, if food == 1 can never be True , so the flow always defaults to the plural form.

You have two options:

if int(food) == 1:

The above code will cast food to an integer type, but will raise an exception if the user does not type a number.

if food == '1':

The above code is checking for the string '1' rather than an integer (note the surrounding quotes).

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

Then you can treat food as an int throughout your code by using %d instead of %s. When entering a non int your program would throw an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM