Equation of second degree in Python

4

The following code computes roots, vertices, and delta of second-degree equations.

The code runs clean the first time, but when I loop it to restart it gives an error:

Traceback (most recent call last):
  File "python", line 58, in <module>
TypeError: 'dict' object is not callable

Remembering that a (coefficient of x²) must be strictly different from 0!

Code:

#Equação de Segundo grau
#CLS
def cls():
    import os
    os.system('cls')
#FUNÇÕES
def delta(a,b,c):
    delta = (b**2) - (4*a*c)
    return {"delta":delta}
def raizes(a,b,c,delta):
    x1 = (-b+ delta**(1.0/2.0)) / (2.0*a)
    x2 = (-b- delta**(1.0/2.0)) / (2.0*a)
    return {"x1":x1,"x2":x2}
def vertices(a,b,delta):
    xv = (-(b))/ (2.0*a)
    yv = (-(delta))/ (4.0*a)
    return {"xv":xv,"yv":yv}
#PERGUNTA
def pergunta(valor):
    try:
        n = int(input("Qual o valor de %s? "%valor))
        return n
    except ValueError:
        n = " "
        return n
#PROGRAMA
valores = ["B","C"]
resposta = []
perguntarNovamente = None
perguntarNovamente2 = True
while True:
    print("Equação de segundo grau - Solução \n(Delta,Raízes e Vértices)")
    print()
    while perguntarNovamente2:
        try:
            a = int(input("Qual o valor de A: "))
            if a == 0:
                perguntarNovamente2 = True
            else:
                perguntarNovamente2 = False
        except ValueError:
            print("'A' Tem que ser um número!")
            continue
    perguntarNovamente2 = True
    for valor in valores:
        perguntarNovamente = True
        while perguntarNovamente:
            res = pergunta(valor)
            if not(isinstance(res, int) or isinstance(res, float)):
                print()
                print("Valor inválido!")
                continue
            else:
                resposta.append(res)
                perguntarNovamente = False
    b, c = resposta[0], resposta[1]
    a = a
    delta = delta(a,b,c)
    raizes = raizes(a,b,c,delta['delta'])
    vertice = vertices(a,b,delta['delta'])
    if delta['delta']<0:
        print()
        print("- Delta: %.2f"%delta['delta'])
        print("- Raízes: Essa função não apresenta uma raiz real!")
        print()
    elif delta['delta']==0:
        print()
        print("- Delta: %.2f"%delta['delta'])
        print("- Raízes: Essa função apresenta uma raiz reais: %.2f"%raizes['x1'])
        print("- X Vértice: %.2f"%vertice['xv'])
        print("- Y Vértice: %.2f"%vertice['yv'])
    else:
        print()
        print("- Delta: %.2f"%delta['delta'])
        print("- Raízes: Essa função apresenta duas raízes reais: %.2f e %.2f"%(raizes['x1'], raizes['x2']))
        print("- X Vértice: %.2f"%vertice['xv'])
        print("- Y Vértice: %.2f"%vertice['yv'])

    while True:
        an = input("Deseja reiniciar? (s/n) ")
        while an not in("s","n"):
            continue
        cls()
        break
    if an == "s":
        continue
    else:
        print("Muito Obrigado")
        break

Link to the code: link

    
asked by anonymous 10.09.2016 / 19:07

1 answer

7

There are conflicts between variables and function names.

You have the functions delta and raizes :

def delta(a,b,c):
    delta = (b**2) - (4*a*c)
    return {"delta":delta}

def raizes(a,b,c,delta):
    x1 = (-b+ delta**(1.0/2.0)) / (2.0*a)
    x2 = (-b- delta**(1.0/2.0)) / (2.0*a)
    return {"x1":x1,"x2":x2}

No While is invoked both functions:

while True:
    print("Equação de segundo grau - Solução \n(Delta,Raízes e Vértices)")
    # ....

    delta = delta(a,b,c)
    raizes = raizes(a,b,c,delta['delta'])

When assigning the result of the delta and raizes functions to the variables of the same name, the functions will no longer be referenced, before the loop , delta and raizes are functions , in the loop from the first iteration, are variables that save the results of the functions.

See the example below:

def foo():
    print ("foo")

foo()       # foo
foo = "bar" 
print (foo) # bar

The fact that foo is originally a function has no influence on what data types can be assigned to it in the future. This is the dynamic typing .

To resolve the problem, rename the delta and raizes variables to something else, for example, d and r or use other names for the functions.

See also:

  • How does dynamic typing work in Python 3.x?
  • >
  • What's the difference between a static and dynamic programming language? li>
  • Python to dynamic language and also strongly typed language

  • 10.09.2016 / 19:53