无法获取raw_input以返回数字

时间:2014-06-08 19:03:47

标签: python string user-input python-2.x

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) 

所以我是代码的新手,这是我的代码。当我使用终端编译它时,我明白了:

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'

有人可以向我解释我做错了吗?

2 个答案:

答案 0 :(得分:3)

raw_input始终返回一个字符串对象。如果您打算将其用作数字对象,则需要将其显式转换为数字对象(对其执行数学运算):

weight = int(raw_input())

#or

weight = float(raw_input())

如果数字始终为整数,请使用int。否则,如果输入可以包含小数部分,例如10.1,则使用float

答案 1 :(得分:1)

raw_input()返回string。您需要将weight投射到浮动:

weight = float(weight)

或者在一行中:

weight = float(raw_input())