简体   繁体   中英

How to fix python error (object is not callable)

So I'm just learning Python now, and I wrote this code to practice:

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

This code seems to return an error after the while loop starts again and I input a weight and height. It works fine the first time, but after I tell it to keep running, and then input the weight and height, it crashes and gives this error:

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

I thought I'd ask here for help because I can't figure out the problem. Thanks!

You're using the symbol bmi in an ambiguous manner.

When you do bmi, report = bmi(weight, height) , you essentially override the usage of this symbol as a reference to a function of the same name.

So in the first iteration it references a function, but in the second iteration it references a (non-callable) variable.

Thus, the advantage on a runtime interpreted language is turned against you.

You are writing

bmi = round(bmi, 1)

which makes bmi a number. On the next iteration of your loop, you write

bmi, report = bmi(weight, height)

using it as a function.

Decide whether bmi is the name of your function of your result, and use it consistently

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM