How to finish code execution in Python 3?

Question:

print('Calcula raizes equação 2º grau')
a = float(input('Informe o Valor de A'))
while a == 0:
    print('a equação não é do segundo grau')
    break
b = float(input('Informe o Valor de B'))
c = float(input('Informe o Valor de C'))
delta = (b ** 2) - 4 * (a * c)
print(delta)
while delta < 0:
    print('A equação não possui raizes reais')
    break
if delta > 0:
    print('possui 2 raizes reais ')
    raizdelta = delta ** 0.5
    print('Raiz de delta',raizdelta)
    x1 = (-b + raizdelta) / (2 * a)
    x2 = (-b - raizdelta) / (2 * a)
    print('x1',x1)
    print('x2',x2)

I'm having a problem when the variable (a = 0) instead of finishing the code execution it continues… what can I do?

Answer:

If what you want is to terminate execution then you should use an exit() and not a break . In fact it should be an if and not a while that doesn't make sense there. If I used it inside a function (which I prefer to do always even to make the code look like a script ) then I could just use a return to finish.

Unless you wanted to ask again, then the while would be adequate, but the logic would be different.

print('Calcula raizes equação 2º grau')
a = float(input('Informe o Valor de A'))
if a == 0:
    print('a equação não é do segundo grau')
    exit()
b = float(input('Informe o Valor de B'))
c = float(input('Informe o Valor de C'))
delta = (b ** 2) - 4 * (a * c)
print(delta)
if delta < 0:
    print('A equação não possui raizes reais')
    exit()
if delta > 0:
    print('possui 2 raizes reais ')
    raizdelta = delta ** 0.5
    print('Raiz de delta',raizdelta)
    x1 = (-b + raizdelta) / (2 * a)
    x2 = (-b - raizdelta) / (2 * a)
    print('x1',x1)
    print('x2',x2)

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

Scroll to Top