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

2024-03-28 13:17:12 发布

您现在位置: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循环再次开始并且我输入了一个权重和高度之后,这段代码似乎返回了一个错误。它第一次运行良好,但在我告诉它继续运行,然后输入重量和高度后,它崩溃并给出以下错误:

^{pr2}$

我想我应该在这里寻求帮助,因为我无法解决问题。 谢谢!在


Tags: to代码nameimportreportinputyourif
2条回答

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

当您执行bmi, report = bmi(weight, height)操作时,实际上会重写此符号作为对同名函数的引用。在

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

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

你在写作

bmi = round(bmi, 1)

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

^{pr2}$

把它当作一个函数。在

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

相关问题 更多 >