Python - 在函数内输入

时间:2013-09-11 00:58:52

标签: python python-2.7

不确定此代码有什么问题,我刚刚开始使用Python 2.7,并且遇到了这个bmi计算器脚本的问题。

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'

1 个答案:

答案 0 :(得分: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)