乘以&在Python中划分非类型和int

时间:2016-12-30 23:32:32

标签: python python-2.7 python-3.x

所以我正在写一个计算你的BMI的简单程序。当我需要通过获取重量和高度的返回值来计算BMI时,我遇到了一个问题(就好像没有返回值一样)。当我在一个函数中包含所有模块时,此代码用于工作,因为我已将所有函数划分为我遇到此问题的单独模块。

>     Error:
>     Traceback (most recent call last):
>       File "C:/OneDrive/Documents/3.py", line 43, in <module>
>         bmi = calcBMI(weight, height)
>       File "C:/OneDrive/Documents/3.py", line 17, in calcBMI
>         bmi = float(weight * 703 / (height * height))
>     TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

这是我的代码:

##########
# Functions
##########
def getweight():
    weight = float(input('Enter your weight in LBs: '))
    if weight <= 0 or weight > 1000:
        print('Weight cannot be less than 0 or greater than 700')
        return weight

def getheight():
    height = float(input('Enter your height in inches: '))
    if height <= 0:
        print('Height cannot be less than 0')
        return height

def calcBMI(weight, height):
    bmi = float(weight * 703 / (height * height))
    return bmi

def printData(name, bmi):
    print(name)
    print('Your BMI is %.2f' % bmi)
    if bmi >= 18.5 and bmi <= 24.9:
        print('Your BMI is normal')
    elif bmi <= 18.5:
        print('Your BMI is underweight')
    elif bmi >= 25 and bmi <= 29.9:
        print('Your BMI is overweight')
    elif bmi >= 30:
        print('**Your BMI is obese**')

#####################
# Beginning of program
#####################
print("Welcome to the Body Mass Index Calculator")

name = input('Enter your name or 0 to quit: ')

# beginning of loop
while name != "0":
    height = getheight()
    weight = getweight()
    bmi = calcBMI(weight, height)
    printData(name, weight, height, bmi)
    name = input('Enter another name or 0 to quit: ')

print("Exiting program...")

2 个答案:

答案 0 :(得分:6)

首先,如果它小于0,则只返回高度。您可能希望从return块中删除if语句。

您可能还想创建一些逻辑来处理输入的错误高度,例如引发异常或将用户返回到提示符。

def getweight():
    weight = float(input('Enter your weight in LBs: '))
    if weight <= 0 or weight > 1000:
        print('Weight cannot be less than 0 or greater than 700')
        #Some code here to deal with a weight less than 0
    return weight

def getheight():
    height = float(input('Enter your height in inches: '))
    if height <= 0:
        print('Height cannot be less than 0')
        #Some code here to deal with a height less than 0
    return height

处理错误权重的一种方法是:

def getweight():
    while True:
        weight = float(input('Enter your weight in LBs: '))
        if weight <= 0 or weight > 1000:
            print('Weight cannot be less than 0 or greater than 700')
        else:
            return weight

您可能希望将此限制为一定数量的迭代 - 由您决定。

答案 1 :(得分:2)

getheightgetweight都不一定会返回一个数字(即if失败时);在这种情况下,它会返回None