2015-08-28 48 views
0

我是一個新手,Python和最近已試圖創建一個BMI計算器,但我用下面的代碼有錯誤:的Python:的raw_input和不支持的操作類型

def calculator(): 

    weight = raw_input('Please enter your weight (kg):') 

    if weight.isdigit and weight > 0: 
     height = raw_input('Please enter your height (m):') 

     if height.isdigit and height > 0: 
      bmi = (weight)/(height ** 2) 

      print "Your BMI is", bmi 

      if bmi < 18.5: 
       print 'You are underweight.' 
      if bmi >= 18.5 and bmi < 25: 
       print 'Your BMI is normal.' 
      if bmi >= 25 and bmi < 30: 
       print 'You are overweight.' 
      if bmi >= 30: 
       print 'You are obese.'  

     else: 
      height = raw_input('Please state a valid number (m):') 


    else: 
     weight = raw_input('Please state a valid number (kg):') 

每當我試着要執行的代碼,我能夠進入的體重和身高,但我則與此錯誤消息面對:

Traceback (most recent call last): 
    File "*location*", line 40, in <module> 
    calculator() 
    File "*location*", line 15, in calculator 
    bmi = (weight)/(height ** 2) 
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' 

我這個愚蠢的問題和錯誤纏身代碼道歉,但我很新的編程並欣賞任何形式的幫助。 :)

+1

你從'raw_input'得到的東西總是在字符串類型中用int() ' – The6thSense

+1

請注意,'weight.isdigit'只引用方法,它實際上不會調用*方法。 –

+0

你的程序中有很多錯誤只是通過python的基礎,然後再試一次,你在這裏試圖完成什麼'如果高度==退出:' – The6thSense

回答

2

raw_input始終返回str對象。您需要明確地將輸入轉換爲int。 您可以做

val = int(raw_input(...)) 

val = raw_input(...) 
val = int(val) 

正如其他人所提到的,在你的代碼中的許多錯誤。這裏是一個:

if height == exit: 

weight相同的問題條件。我只是想指出,因爲你沒有問這個問題,所以我會讓你找出問題是什麼:)。

2

請使用這種方式

def calculator(): 

    weight = int(raw_input('Please enter your weight (kg):')) 

    if weight >0 and weight > 0: 
     height = int(raw_input('Please enter your height (m):')) 

     if height >0 and height > 0: 
      bmi = (weight)/(height ** 2) 

      print "Your BMI is", bmi 

      if bmi < 18.5: 
       print 'You are underweight.' 
      if bmi >= 18.5 and bmi < 25: 
       print 'Your BMI is normal.' 
      if bmi >= 25 and bmi < 30: 
       print 'You are overweight.' 
      if bmi >= 30: 
       print 'You are obese.'  

     else: 
      height = int(raw_input('Please state a valid number (m):')) 
     if height == exit: 
      exit() 

    else: 
     weight = int(raw_input('Please state a valid number (kg):')) 

    if weight == exit: 
     exit() 

你需要轉換的輸入項爲int,因爲它們都是字符串。

而且你不再需要檢查它是否是一個數字,

不過,我建議你添加另一個條件,如:

if weight and height: 
    #Do stuff 

如果沒有提供任何條目。

編輯:!

/\如果你需要小數扮演他們漂浮

1

進入應轉換爲浮動號碼。只需更改 bmi = float(weight)/(float(height)** 2) 你很好走

相關問題