如果输入可以有小数部分,如
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)
所以我是新的代码,这是我的代码。当我使用terminal编译它时,得到如下结果:
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'
谁能告诉我我做错了什么? raw_input
总是返回一个字符串对象。如果您打算这样使用它(对其执行数学运算),则需要显式地将其转换为数字对象:
weight = int(raw_input())
#or
weight = float(raw_input())
如果数字总是整数,则使用int
。
10.1
,则使用float
。 raw_input()
返回string
。您需要将weight
转换为float:
weight = float(weight)
或者一行:
weight = float(raw_input())