所以我正在编写一个简单的程序来计算您的 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...")
最佳答案
首先,如果高度小于 0,您只返回高度。您可能希望从 if
block 中删除 return
语句。
您可能还想创建一些逻辑来处理输入的不正确高度,例如引发异常或将用户返回到提示。
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
您可能希望将此限制为一定的迭代次数 - 由您决定。
关于python - 在 Python 中乘除非类型和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403989/