Python:raw_input和不受支持的操作数类型 [英] Python: raw_input and unsupported operand type(s)
问题描述
我是Python的新手,最近一直在尝试创建BMI计算器,但是以下代码出现错误:
I am a newbie to Python and have been recently attempting to create a BMI calculator, but I am having errors with the following code:
def calculator():
weight = raw_input('Please enter your weight (kg):')
if weight.isdigit and weight > 0:
height = raw_input('Please enter your height (m):')
if height.isdigit and height > 0:
bmi = (weight) / (height ** 2)
print "Your BMI is", bmi
if bmi < 18.5:
print 'You are underweight.'
if bmi >= 18.5 and bmi < 25:
print 'Your BMI is normal.'
if bmi >= 25 and bmi < 30:
print 'You are overweight.'
if bmi >= 30:
print 'You are obese.'
else:
height = raw_input('Please state a valid number (m):')
else:
weight = raw_input('Please state a valid number (kg):')
每当我尝试执行代码时,我都可以输入体重和身高,但是随后我会遇到以下错误消息:
Whenever I try to execute the code, I am able to enter weight and height, but I am then confronted with this error message:
Traceback (most recent call last):
File "*location*", line 40, in <module>
calculator()
File "*location*", line 15, in calculator
bmi = (weight) / (height ** 2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
我为这个愚蠢的问题和错误缠身的代码表示歉意,但是我对编程非常陌生,并感谢任何形式的帮助. :)
I apologize for this dumb question and error-ridden code, but I am very new to programming and appreciate any kind of help. :)
推荐答案
raw_input
始终返回str
对象.您需要将输入显式转换为int
.
你可以做
raw_input
always returns a str
object. You need to explicitly convert the input to an int
.
You can either do
val = int(raw_input(...))
或
val = raw_input(...)
val = int(val)
正如其他人所提到的,您的代码中有很多错误.这是一个:
As others have mentioned, there are many errors in your code. Here is one:
if height == exit:
与weight
条件相同的问题.我只是要指出一点,因为您没有问这个问题,所以我将让您找出问题所在:).
Same problem with weight
condition. I am just going to point out as you didn't ask about this in question so I will let you find out what the problem is :).
这篇关于Python:raw_input和不受支持的操作数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!