Is there any command to terminate the program in Python?

0

For example, I'm writing a code

def soma(): 

 n1=int(input('digite um numero'))
 n2=int(input('digite outro'))

 soma = n1+n2

 print('A soma de {} e {} é {}'.format(n1,n2,soma))

#começo do programa

p=input('Você deseja somar?')

if p=='sim':
  print(soma())

print('Deseja subtrair')

.....

If I want to terminate my code in the sum function, is there any way I can not make the program execute the other lines?

    
asked by anonymous 05.03.2018 / 13:25

2 answers

1

In your example, would it help if you put an else clause? Something like this:

p=input('Você deseja somar?')

if p=='sim':
  print(soma()) # Realiza somente a soma caso a condição seja verdadeira
else:
  print('Deseja subtrair') # Realiza somente esse trecho caso a condição seja falsa
    
05.03.2018 / 13:44
1

Python has in fact a way to finish executing the program by doing:

sys.exit(0)

Assuming you previously included the sys library:

import sys

In your case it would look like this:

import sys # importação aqui
def soma(): 

 n1=int(input('digite um numero'))
 n2=int(input('digite outro'))

 soma = n1+n2

 print('A soma de {} e {} é {}'.format(n1,n2,soma))
 system.exit(0) # terminar o programa aqui

This output is made at the expense of a System.Exit exception, as you can see in the documentation , which allows the program to perform cleanup actions. The 0 parameter passed indicates that the program ended successfully.

Note : Although it works in this way the best would be to change the flow of the program, as the response from @escapistabr showed, because it is clearer to realize how the program follows, and ends up being simpler than this.     

05.03.2018 / 13:58