5

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.

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for your help. He might have mentioned that raw_input was always returning a string, but I might have forgotten. It works fine now, thank you for your help.
@Matt If you find it helpful, accept Narpar1217's answer as a valid answer.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.