所以我寫了一個簡單的程序來計算你的BMI。通過獲取體重和身高的返回值(它的行爲就好像沒有返回的值),計算體重指數時,我遇到了一個問題。當我將所有模塊放在一個函數中時,此代碼用於工作,因爲我已將所有函數劃分爲我遇到此問題的單獨模塊。在Python中乘以和除非非類型和int
> 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...")
好的,我明白了。現在,如果'如果'沒有失敗,爲什麼它不會返回一個值?根據我所瞭解的情況,我收到了一個類型錯誤,因爲我的非類型在被調用時可能沒有賦值給它 – No1ukno
你怎麼知道這種情況正在發生? –
我想我不確定是否是這種情況。我假設它沒有分配我輸入的值,因爲它是作爲類型錯誤返回的。我仍在學習,所以我正在吸收所有這些信息。謝謝您的回覆。 – No1ukno