简体   繁体   中英

Why does “TypeError: 'undefined' object is not callable” come up?

subtotal = input("What's the Subtotal?") #input of dinners subtotal
tax_input = input("What's the tax there?") #local tax
tip_input = .20 #average tax is 20%
tax = subtotal * tax_input #tax
tip = subtotal * tip_input #tip
total = subtotal + tax + tip #totalling
print "Your %s was " + tax (tax)
print "Your %s was " + tip (tip)
print "Your %s is " + total (total)

What does the error "TypeError: 'undefined' object is not callable" mean? Also, is my code good? I know that instead of using two tax's I can just change the value, but that seems weird to me...

Changing your prints as follows should help:

print("Your tax was {} ".format(tax))
print("Your tip was {}".format(tip))
print("Your total is {}".format(total))

Your code does not work, because tax, tip and total are not functions or callable objects. They just numbers.

Did you want to do something like that?

subtotal = input("What's the Subtotal?") #input of dinners subtotal
tax_input = input("What's the tax there?") #local tax
tip_input = .20 #average tax is 20%
tax = subtotal * tax_input #tax
tip = subtotal * tip_input #tip
total = subtotal + tax + tip #totalling
print "Your tax was %s" %tax
print "Your tip was %s" %tip
print "Your total is %s" %total

The problem in your code is this

print "Your %s was " + tax (tax)

tax is not a method so you can't call it. Your tax is either int or float , so you need to make it a string to concatenate, either by doing this

print "Your tax was %s" %tax

or

print "Your tax was " + str(tax)

You are trying to call tax, tip and total as if they were functions. They are variables, and not functions. If you want to replace the strings tax, tip, and total with their respective "titles" you would need to take an approach that uses iterate-able key/value hash (which python conveniently makes easy, but that's for another discussion).

Instead you could simply do something like:

`
print "Your tax was", tax
print "Your tip was", tip
print "Your total was", total
`

The truth is your code sucks. So does mine. It will probably always suck. Get used to regularly looking back on code you've written before and hating yourself for writing such horrible, wretched code in the first place.

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