How do I fix this “TypeError: 'str' object is not callable” error?

泪湿孤枕 提交于 2020-01-21 02:57:17

问题


I'm creating a basic program that will use a GUI to get a price of an item, then take 10% off of the price if the initial price is less than 10, or take 20% off of the price if the initial price is greater than ten:

import easygui
price=easygui.enterbox("What is the price of the item?")
if float(price) < 10:
    easygui.msgbox("Your new price is: $"(float(price) * 0.1))
elif float(price) > 10:
    easygui.msgbox("Your new price is: $"(float(price) * 0.2))

I keep getting this error though:

easygui.msgbox("Your new price is: $"(float(price) * 0.1))
TypeError: 'str' object is not callable`

Why am I getting this error?


回答1:


You are trying to use the string as a function:

"Your new price is: $"(float(price) * 0.1)

Because there is nothing between the string literal and the (..) parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:

>>> "Hello World!"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Seems you forgot to concatenate (and call str()):

easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))

The next line needs fixing as well:

easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))

Alternatively, use string formatting with str.format():

easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))

where {:02.2f} will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.



来源:https://stackoverflow.com/questions/16873727/how-do-i-fix-this-typeerror-str-object-is-not-callable-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!