为什么我收到错误,“不能将序列乘以'int'类型的非int”?

时间:2016-10-21 15:26:48

标签: python-2.7

def bmi(weight,height):
    """bmi calculates anyones bmi.
    weight=weight in pounds,height=someones height in inches,
    this function returns the person's body mass index"""
    weight_calc=weight*0.45  #converts weight to kilograms
    height_calc=height*0.025  #converts height to meters
    square=height_calc**2
    calc=weight_calc/square #final bmi calculation
    print 'For someone who is',height,'inches tall, and  
    weighs',weight,'pounds, their body mass index is',calc 



def new_bmi():
    """asks someone their height in inches, and weight in pounds.Then
    calcs bmi"""
    tall=raw_input('How tall are you in inches?\n')
    heavy=raw_input('How much do you weigh in pounds?\n')
    print 'You are',tall,'inches tall, and weigh',heavy,'pounds.'
    float(heavy)
    bmi(heavy,tall)



new_bmi()

我必须编写一个程序,询问某人他们的身高(英寸)和体重(磅),然后使用该信息使用bmi函数计算他们的BMI。我一直收到错误:'不能将序列乘以非'int'类型'float'“

感谢任何回复,非常感谢

1 个答案:

答案 0 :(得分:1)

weight_calc=weight*0.45中,变量weight是来自用户输入的字符串,而不是float或int。它后面的行会遇到同样的问题。在代码中的某个点上,如果需要十进制值,则需要将权重和高度转换为浮点数,如果只需要整数,则需要转换为int。我建议你在调用bmi函数时进行转换:

#bmi(heavy,tall) #this is passing heavy and tall as strings, not numbers
bmi(float(heavy),float(tall)) #<-- use this instead

输出:

('For someone who is', 60.0, 'inches tall, and weighs', 160.0, 'pounds, their body mass index is', 32.0)