Can't get raw_input to return a number

喜你入骨 提交于 2019-12-20 07:47:43

问题


print "How old are you?",
age = raw_input()
print "How tall are you in inches?",
height = raw_input()
print "How much do you weigh in pounds",
weight = raw_input()

print "So, you are %r years old, %r inches tall, and %d kilograms." % (
age, height, weight / 2.2) 

So I am new to code and this is my code. When I use terminal to compile it, I get this:

How old are you? 1
How tall are you in inches? 1
How much do you weigh in pounds 1
Traceback (most recent call last):
  File "ex11.py", line 9, in <module>
   age, height, weight / 2.2) 
TypeError: unsupported operand type(s) for /: 'str' and 'float'

Can someone please explain to me what I did wrong?


回答1:


raw_input always returns a string object. You need to explicitly convert this into a number object if you plan to use it as such (perform mathematical operations on it):

weight = int(raw_input())

#or

weight = float(raw_input())

Use int if the number will always be an integer. Otherwise, use float if the input can have a decimal part such as 10.1.




回答2:


raw_input() returns a string. You will need to cast your weight to float:

weight = float(weight)

Or in one line:

weight = float(raw_input())


来源:https://stackoverflow.com/questions/24109770/cant-get-raw-input-to-return-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!