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

前端 未结 2 1768
野的像风
野的像风 2021-01-02 00:06

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 pric

相关标签:
2条回答
  • 2021-01-02 00:14

    this part :

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

    asks python to call this string:

    "Your new price is: $"

    just like you would a function: function( some_args) which will ALWAYS trigger the error:

    TypeError: 'str' object is not callable

    0 讨论(0)
  • 2021-01-02 00:26

    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.

    0 讨论(0)
提交回复
热议问题