在python中添加浮点数

时间:2014-11-08 20:59:20

标签: python python-3.x

尝试将所有BMI结果一起添加然后显示,不断收到错误:

TypeError: 'float' object is not iterable

在计算bmi>后运行我的程序时,还会继续打印无效?

def bmirange():
if bmi >= 25.0:
    print('Your BMI measurement shows that you are overweight')
elif bmi <18.0:
        print('Your BMI measurement shows that you are underweight')
else:
        print('Your BMI measurement shows that you are in the healty weight band')




weight = float(input('What is your weight in Kg? '))
height = float(input('What is your height in Meters? '))
bmi = weight / (height * height)
print(bmi)
print(bmirange())

bmiredo = input('Do you want to do another BMI measurement?, y / n ')

while bmiredo == 'y':
weight = float(input('What is your weight in Kg? '))
height = float(input('What is your height in Meters? '))
print(bmi)
print(bmirange())
bmiredo = input('Do you want to do anoher BMI measurement?, y / n ')
else:
print('ok, the total of your BMI results are')

print(sum(bmi))

input('press the enter key to exit')

1 个答案:

答案 0 :(得分:1)

问题在于:

print(sum(bmi))

bmi变量是一个数字,但如果您想使用sum(),则需要一个数字列表。以下是如何收集数字列表的方法。 .append()方法将一个元素添加到列表的末尾。

bmi_list = []
...
bmi = weight / height**2
bmi_list.append(bmi)
...
while ...:
    ....
    bmi = weight / height**2
    bmi_list.append(bmi)
    ...
...
print(sum(bmi_list))

注意

bmirange()也有错误:print()被调用两次。您可以将print()置于bmirange()内,也可以print() bmirange()的结果,但同时执行这两项操作会导致None被打印出来,我认为不是你想要的。

解决方案1 ​​

def bmirange():
    if bmi >= 25.0:
        print('Your BMI measurement shows that you are overweight')
    elif bmi <18.0:
        print('Your BMI measurement shows that you are underweight')
    else:
        print('Your BMI measurement shows that you are in the healty weight band')

...

bmirange() # will print itself

解决方案2

def bmirange():
    if bmi >= 25.0:
        return 'Your BMI measurement shows that you are overweight'
    elif bmi <18.0:
        return 'Your BMI measurement shows that you are underweight'
    else:
        return 'Your BMI measurement shows that you are in the healty weight band'

...

print(bmirange()) # will not print itself