【问题标题】:TypeError: 'int' object is not callable: QuadraticTypeError:'int'对象不可调用:二次
【发布时间】:2013-01-04 05:53:32
【问题描述】:

(在没有导入的二次方程中查找 x 的值。)每当我运行程序时,Python 都会停在 discriminant = (b ** 2) - 4(a * c) 并显示 TypeError: 'int' object is not callable。怎么了?

#------SquareRootDefinition---------#
def Square_Root(n, x):
if n > 0:
    y = (x + n/x) / 2
    while x != y:
        x = y
        return Square_Root(n, x)
    else:
        if abs(10 ** -7) > abs(n - x ** 2):
            return y
elif n == 0:
    return 0
else:
    return str(int(-n)) + "i"

#----------Quadratic Equation--------------#

a = input("Enter coefficient a: ")
while a == 0:
    print "a must not be equal to 0."
    a = input("Enter coefficient a: ")
b = input("Enter coefficient b: ")
c = input("Enter coefficient c: ")

def Quadratic(a, b, c):
    discriminant = (b ** 2) - 4(a * c)
    if discriminant < 0:
        print "imaginary"
    elif discriminant >= 0:
        Sqrt_Disc = Square_Root(discriminant)
        First_Root = (-b + Sqrt_Disc) / (2 * a)
        Second_Root = (-b - Sqrt_Disc) / (2 * a)

  return First_Root, Second_Root

X_1, X_2 = Quadratic(a, b, c)

【问题讨论】:

  • 顺便说一句,代码还没写完。

标签: python error-handling python-2.7 quadratic


【解决方案1】:

4(a * c) 不是有效的 Python。你的意思是4 * a * c。您可以在数学符号中使用并列并省略乘法符号,但在 Python(或大多数其他编程语言)中不能。

【讨论】:

  • 谢谢@BrenBarn。你的意思是唯一的问题是操作?
  • @user1947570:唯一的问题是您编写操作的方式。您必须实际编写乘法符号 (*)。
  • 想象一下,如果你写了a (b * c)a 是一个函数吗?或者a 是你想要增加的东西吗?由于这种模糊性,乘法不能是隐含的。
【解决方案2】:

您正在尝试将4 用作函数:

discriminant = (b ** 2) - 4(a * c)

你错过了*

discriminant = (b ** 2) - 4 * (a * c)

另外,如果你的判别式低于 0,你会得到一个未绑定的本地异常:

>>> X_1, X_2 = Quadratic(2, 1, 1)
imaginary
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in Quadratic
UnboundLocalError: local variable 'First_Root' referenced before assignment

您需要在此处添加return,或者更好的是,引发异常:

def Quadratic(a, b, c):
    discriminant = (b ** 2) - 4(a * c)
    if discriminant < 0:
        raise ValueError("imaginary")
    elif discriminant >= 0:
        Sqrt_Disc = Square_Root(discriminant)
        First_Root = (-b + Sqrt_Disc) / (2 * a)
        Second_Root = (-b - Sqrt_Disc) / (2 * a)

    return First_Root, Second_Root

您的Square_Root() 函数缺少x 的默认值:

def Square_Root(n, x=1):

通过这些更改,您的功能实际上可以工作:

>>> Quadratic(1, 3, -4)
(1, -4)

【讨论】:

  • 帮助:由于 Square_Root 函数需要 2 个参数,我应该在 Sqrt_Disc = Square_Root(discriminant) 中添加什么才能让 Quadratic 工作?
  • @user1947570:你的意思是你不知道如何使用递归函数Square_Root()?啧啧。啧啧。
  • 非常感谢@Martjin Pieters。
【解决方案3】:

您需要做4 * (a * c) 或只是4 * a * c 因为python 认为您正在尝试调用函数4

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 2013-04-03
    • 2017-12-20
    • 2023-03-03
    相关资源
    最近更新 更多