我如何解决这个“TypeError:'str'对象不可调用”错误? [英] How do I fix this "TypeError: 'str' object is not callable" error?
问题描述
我正在创建一个基本程序,使用GUI获取项目的价格,然后如果初始价格低于10,则从价格中减去10%,如果初始价格低于10,则使用价格的20%初始价格大于十:
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))
b $ b
我仍然收到这个错误:
I keep getting this error though:
easygui.msgbox("Your new price is: $"(float(price) * 0.1))
TypeError: 'str' object is not callable`
为什么会收到此错误?
推荐答案
:
"Your new price is: $"(float(price) * 0.1)
因为字符串文字和<$ c $ c>(..)括号之间没有什么,将该字符串解释为可调用的并且用一个参数调用它的指令:
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
似乎你忘了连接 str()
):
easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))
下一行需要修复well:
The next line needs fixing as well:
easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))
或者,使用字符串格式 str.format()
:
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))
code> {:02.2f} 将替换为您的价格计算,将浮点值格式化为具有2位小数的值。
where {:02.2f}
will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.
这篇关于我如何解决这个“TypeError:'str'对象不可调用”错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!