Python second degree equation

Asked

Viewed 13,627 times

4

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

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

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

Recalling that the a (x² coefficient) has to 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

Code link: https://repl.it/D2b9/3

  • Avoid placing the code externally, except as an extra thing.

  • You commented that it gives an error when you make the loop, but what mistake? Supplement your question. :-)

2 answers

8


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}

In the While both functions are invoked:

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 function output delta and raizes for variables of the same name, functions will no longer be referenced before the loop, delta and raizes are functions, in the loop from the first iteration, are variables that store the results of the functions.

See the example below:

def foo():
    print ("foo")

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

The fact of foo originally being a function does not have any influence on what types of data can be assigned to it in the future. That’s the dynamic typing.

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

See also:

  1. How dynamic typing works in Python 3.x?
  2. What is the difference between a static and dynamic programming language?
  3. Why is Python a Dynamic language and also a strongly typed language

-1

print('equação do 2° gral')
print('x²-x+1=0, a = x², b = x, c = 1')
a = int(input('De valor à a'))
b = int(input('De valor à b'))
c = int(input('De valor à c'))
print('A formula é (b*b - 4*a*c)')
delta= b*b-4*a*c
print('delta é {}'.format(delta))
print('Ainda não acabamos')
x = (-b - (delta)**(1/2)/(2*a)
x1 = (-b + (delta)**(1/2)/(2*a)
print('x1 = {}, x2 = {}'.format(x1, x))
  • 1

    You could bring along to your code a brief explanation of what it does?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.