2016-12-30 67 views
2

所以我寫了一個簡單的程序來計算你的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...") 

回答

2

getheight都不也不getweight一定返回一個數字(即,當if失敗);在這種情況下,它返回None

+0

好的,我明白了。現在,如果'如果'沒有失敗,爲什麼它不會返回一個值?根據我所瞭解的情況,我收到了一個類型錯誤,因爲我的非類型在被調用時可能沒有賦值給它 – No1ukno

+0

你怎麼知道這種情況正在發生? –

+0

我想我不確定是否是這種情況。我假設它沒有分配我輸入的值,因爲它是作爲類型錯誤返回的。我仍在學習,所以我正在吸收所有這些信息。謝謝您的回覆。 – No1ukno

6

首先,如果返回高度小於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 

您可能希望這限制到特定數量的迭代 - 由您決定。

+0

更好:添加一個循環(對每個)。 –

+0

非常感謝!我沒有意識到錯誤是多麼簡單。我已經從這兩個模塊中刪除了if塊,並且代碼正常工作。 – No1ukno

相關問題