如何修复python错误(对象不可调用)

时间:2019-05-06 11:34:38

标签: python

所以我现在正在学习Python,我编写了以下代码进行练习:

import time
from decimal import Decimal

name = input("\nPlease enter your name: ")

def bmi(weight, height):
    bmi = weight/(height**2)
    if bmi > 29.9:
        report = "obese"
    elif bmi <= 29.9 and bmi > 24.9:
        report = "overweight"
    elif bmi <= 24.9 and bmi > 18.5:
        report = "normal"
    elif bmi <= 18.5:
        report = "underweight"
    else:
        report = "to be lying"
    return (bmi, report)

while True:

    weight = Decimal(input("\nEnter your weight (kg): "))
    if weight == 0:
        print("You can't have a weight of 0. Try again!")
        continue
    if weight < 0:
        print("A negative weight? Really?")
        continue

    height = Decimal(input("Enter your height (cm): "))
    height = height/100

    bmi, report = bmi(weight, height)
    bmi = round(bmi, 1)
    time.sleep(1)
    print("\n" + name.title() + ", according to your BMI (" + str(bmi) +
        "), you are considered " + report + ".")

    qprompt = input("\nDo you wish to quit? (y/n): ")
    if qprompt == 'y':
        break
    else:
        continue

这段代码似乎在while循环再次开始并且我输入了体重和身高后返回了错误。第一次可以正常运行,但是在我告诉它继续运行,然后输入重量和高度后,它崩溃了,并显示以下错误:

Traceback (most recent call last):
  File "BMI2.py", line 33, in <module>
    bmi, report = bmi(weight, height)
TypeError: 'decimal.Decimal' object is not callable

我想在这里寻求帮助,因为我无法弄清楚问题所在。 谢谢!

2 个答案:

答案 0 :(得分:0)

您正在以不明确的方式使用符号bmi

执行bmi, report = bmi(weight, height)时,实际上将覆盖此符号的使用,以作为对同名功能的引用。

因此,在第一次迭代中,它引用了一个函数,但是在第二次迭代中,它引用了一个(不可调用的)变量。

因此,运行时解释语言的优势对您不利。

答案 1 :(得分:0)

您正在写

bmi = round(bmi, 1)

这使bmi成为数字。在循环的下一个迭代中,您编写

bmi, report = bmi(weight, height)

将其用作功能。

确定bmi是否是结果函数的名称,并始终使用它