我是Python的新手并且最近一直在尝试创建BMI计算器,但我在使用以下代码时遇到错误:
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):')
每当我尝试执行代码时,我都可以输入权重和高度,但我会遇到此错误消息:
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'
我为这个愚蠢的问题和错误代码道歉,但我对编程非常陌生,并感谢任何帮助。 :)
答案 0 :(得分:2)
raw_input
始终返回str
个对象。您需要将输入显式转换为int
。
你可以做到
val = int(raw_input(...))
或
val = raw_input(...)
val = int(val)
正如其他人所提到的,您的代码中存在许多错误。这是一个:
if height == exit:
与weight
条件相同的问题。我只是要指出,因为你没有问过这个问题所以我会让你找出问题所在:)。
答案 1 :(得分:2)
请以这种方式使用
def calculator():
weight = int(raw_input('Please enter your weight (kg):'))
if weight >0 and weight > 0:
height = int(raw_input('Please enter your height (m):'))
if height >0 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 = int(raw_input('Please state a valid number (m):'))
if height == exit:
exit()
else:
weight = int(raw_input('Please state a valid number (kg):'))
if weight == exit:
exit()
您需要将输入条目转换为int,因为它们是字符串。
你不再需要检查它是否是数字,
不过,我建议您添加另一个条件:
if weight and height:
#Do stuff
如果没有提供参赛作品。
编辑:
/!\如果您需要小数,请将它们转换为浮动
答案 2 :(得分:1)
输入的数字应转换为浮点数。只是改变了 bmi =浮动(重量)/(浮动(高度)** 2) 你很高兴