我如何解决这个“TypeError:'str'对象不可调用”错误? [英] How do I fix this "TypeError: 'str' object is not callable" error?

查看:1475
本文介绍了我如何解决这个“TypeError:'str'对象不可调用”错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个基本程序,使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆