0

我是 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'

对于这个愚蠢的问题和错误缠身的代码,我深表歉意,但我对编程非常陌生,并感谢任何形式的帮助。:)

4

3 回答 3

2

raw_input总是返回一个str对象。您需要将输入显式转换为int. 你可以做

val = int(raw_input(...))

或者

val = raw_input(...)
val = int(val) 

正如其他人所提到的,您的代码中有很多错误。这是一个:

if height == exit:

条件也有同样的问题weight。我只是要指出,因为你没有问这个问题,所以我会让你找出问题所在:)。

于 2015-08-28T17:00:58.657 回答
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

如果没有提供条目。

编辑:

/!\ 如果您需要小数,请将它们转换为浮动

于 2015-08-28T17:02:05.933 回答
1

输入的数字应转换为浮点数。只需更改 bmi = float(weight)/(float(height)** 2) 你很好

于 2015-08-28T17:12:15.197 回答