如何解决此“ TypeError:'str'对象不可调用”错误?

发布于 2021-01-29 16:00:19

我正在创建一个基本程序,该程序将使用GUI来获取商品的价格,如果初始价格小于10,则从价格中减去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))

我仍然收到此错误:

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

为什么会出现此错误?

关注者
0
被浏览
161
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您正在尝试将字符串用作函数:

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

    因为字符串文字和(..)括号之间没有任何内容,所以Python将其解释为将字符串视为可调用并使用一个参数调用它的指令:

    >>> "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))
    

    下一行也需要修复:

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

    另外,也可以使用字符串格式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))
    

    在那里{:02.2f}会被你的价格计算被替换,格式化浮点值与2位小数的值。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看