use*_*381 12 python string comparison user-interface callable
我正在创建一个基本程序,它将使用GUI来获取商品的价格,如果初始价格低于10,则从价格中扣除10%,或者如果初始价格是,则从价格中取20%的折扣大于十:
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))
Run Code Online (Sandbox Code Playgroud)
我不断收到此错误:
easygui.msgbox("Your new price is: $"(float(price) * 0.1))
TypeError: 'str' object is not callable`
Run Code Online (Sandbox Code Playgroud)
为什么我收到此错误?
Mar*_*ers 21
您正在尝试将字符串用作函数:
"Your new price is: $"(float(price) * 0.1)
Run Code Online (Sandbox Code Playgroud)
因为字符串文字和(..)括号之间没有任何内容,Python将其解释为将字符串视为可调用的指令并使用一个参数调用它:
>>> "Hello World!"(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)
好像你忘了连接(和调用str()):
easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))
Run Code Online (Sandbox Code Playgroud)
下一行也需要修复:
easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))
Run Code Online (Sandbox Code Playgroud)
或者,使用字符串格式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))
Run Code Online (Sandbox Code Playgroud)
在那里{:02.2f}会被你的价格计算被替换,格式化浮点值与2位小数的值.