How to finish executing code in Python 3?

Asked

Viewed 3,811 times

4

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 trouble when the variable (a = 0) instead of finishing the execution of the code it continues... what can I do?

1 answer

5


If you want to close the execution then you should use a exit() and not a break. It should actually be a if and not a while that makes no sense there. If used within a function (that I prefer to always do up to take the face of script code) then could only use one return to close.

Unless you wanted to ask again, then the while would be appropriate, 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)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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