2016-03-14 55 views
0

我使用Python 3.5.1,我需要使用公式703 * weight/height^2來製作一個BMI計算器,輸入我的身高和體重後,我得到「TypeError:不能乘以非序列'str'的類型「如何修復我的代碼以計算Python的身體質量指數?

而且我老實說不知道如何解決它。這是我的代碼。

def calculateBMI(): 
    weight = input("Please enter weight in pounds: ") 
    height = input("Please enter height in inches: ") 

    return weight * ((703.0)/(height * height)) 

bmi = calculateBMI() 

print ("""Your BMI is""", str(bmi)) 

if bmi < 18.5: 
    print("You are underweight.") 
elif bmi > 25: 
    print("You are overweight.") 
else: 
    print ("You are of optimal weight.") 
+2

請問您真正的程序有任何縮進? –

+2

你使用的是Python2還是Python3?Python2具有'raw_input',而Python3則不具備'raw_input'。 –

+1

你運行的是哪個版本的python? raw_input是特定於python2 – snakecharmerb

回答

4

有你的程序中的三個錯誤:

  • 由於您使用Python3,你需要使用input(),不raw_input()讀取用戶的體重和身高。

  • 您需要使用int()float()將用戶數據轉換爲數字類型。

  • 您的縮進不正確。

這是一個可行的方案:

def calculateBMI(): 
    weight = int(input("Please enter weight: ")) 
    height = int(input("Please enter height: ")) 

    return weight * ((703.0)/(height * height)) 
bmi = calculateBMI() 

print ("""Your BMI is""", str(bmi)) 

if bmi < 18.5: 
    print("You are underweight.") 
elif bmi > 25: 
    print("You are overweight.") 
else: 
    print ("You are of optimal weight.") 
+0

非常感謝!這確實有用。我還增加了「以磅爲單位」的重量和「以英寸爲單位」的高度,這樣就不那麼容易混淆了。 – AnEnigma

0

之前我幫幫忙,我只是想指出的是您粘貼代碼沒有縮進。 Python是縮進敏感的 - 你只是把它粘貼錯了,或者你的代碼實際上看起來如何? :)

現在,大概有兩個問題在這裏:

  1. Python版本

當我嘗試運行此代碼,它能夠把從 命令行輸入罰款。我正在使用Python 2.7.8。 raw_input方法 已在Python 3中重命名爲input。因此,如果您使用的是Python 3的 ,則應將raw_input更改爲input

如果你是在Linux上,你可以找到你的Python版本的控制檯這樣的:

$ python --version 
  • 浮標和字符串
  • 當您從命令行輸入數據時,使用inputraw_input,將其保存爲字符串,如文檔

    https://docs.python.org/3/library/functions.html#input

    如果您想將兩個值相乘在一起,你必須將它們轉換爲浮動,就像這樣:

    weight = float(input("Please enter weight: ")) 
    height = float(input("Please enter height: ")) 
    

    我希望這能解決你的問題:)