问题
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