[英]Can't multiply sequence by non-int of type 'float' in Python
[英]Multiply & Divide Non-type and int in Python
所以我正在寫一個計算你的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
塊中刪除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
您可能希望將此限制為一定數量的迭代 - 由您決定。
getheight
和getweight
都不一定會返回一個數字(即當if
失敗時); 在這種情況下,它返回None
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.