Question

(Finding the values of x in a quadratic equation w/o importing.) Whenever I run the program, Python stops at discriminant = (b ** 2) - 4(a * c) and shows TypeError: 'int' object is not callable. What's wrong?

#------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)
Était-ce utile?

La solution 2

You are trying to use 4 as a function:

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

You missed *:

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

Also, if your discriminant turns out to be lower than 0, you'll get an unbound local exception:

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

You'll need to add a return there, or better still, raise an exception:

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

Your Square_Root() function is missing it's default value for x:

def Square_Root(n, x=1):

With those changes, your function actually works:

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

Autres conseils

4(a * c) is not valid Python. You mean 4 * a * c. You can use juxtaposition and omit the multiplication symbol in mathematical notation, but not in Python (or most other programming languages).

You need to do 4 * (a * c) or just 4 * a * c because python thinks you are trying to call a function 4

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top