2013-09-11 42 views
0

不知道這段代碼有什麼問題,我剛開始使用Python 2.7,並且遇到了這個bmi計算器腳本的問題。Python - 函數內輸入

def bmi_calculator(): 

    print "Enter your appelation (Mr., Mrs., Dr., ...): " 
    appelation = raw_input() 
    print "Enter your first name: " 
    fname = raw_input() 
    print "Enter your last name: " 
    lname = raw_input() 
    print "Enter your height in inches: " 
    height = raw_input() 
    print "Enter your weight in pounds: " 
    weight = raw_input() 

    feet = (height/12) 
    inches = (height-feet)*12 
    bmi = ((weight/(height*height))*703) 

    print "BMI Record for %s %s %s:" % (appelation,fname,lname) 
    print "Subject is %d feet %d inches tall and weighs %d pounds" % (feet,inches,weight) 
    print "Subject's BMI is %d" % (bmi) 

有人會告訴我我做錯了什麼嗎?


這是錯誤

Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "a1.py", line 88, in bmi_calculator 
feet = (height/12) 
TypeError: unsupported operand type(s) for /: 'str' and 'int' 
+0

到底是什麼問題? – thefourtheye

+5

您需要將輸入轉換爲數字,默認情況下它們是字符串。 – thefourtheye

回答

4

你需要從str轉換爲數字類型,如float

def bmi_calculator(): 
    print "Enter your appelation (Mr., Mrs., Dr., ...): " 
    appelation = raw_input() 
    print "Enter your first name: " 
    fname = raw_input() 
    print "Enter your last name: " 
    lname = raw_input() 
    print "Enter your height in inches: " 
    height = float(raw_input()) 
    print "Enter your weight in pounds: " 
    weight = float(raw_input()) 
    feet = float((height/12)) 
    inches = (height-feet)*12 
    bmi = ((weight/(height*height))*703) 
    print "BMI Record for %s %s %s:" % (appelation,fname,lname) 
    print "Subject is %d feet %d inches tall and weighs %d pounds" % (feet,inches,weight) 
    print "Subject's BMI is %d" % (bmi)