If…else statement issue with raw_input on Python

前端 未结 2 1213
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 23:41

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

相关标签:
2条回答
  • 2020-12-11 23:49

    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.

    0 讨论(0)
  • 2020-12-12 00:04

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

    0 讨论(0)
提交回复
热议问题