Is there a command to finish the program in Python?

Asked

Viewed 2,574 times

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 finish my code in the sum function, is there any way not to make the program run the other lines?

2 answers

1


In this example of yours, it would help if you put a clause Else? Something like that:

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
  • Oh yes rs, vdd. I didn’t even care. .

1

Python actually has a way to finish the program execution by doing:

sys.exit(0)

Assuming you previously included the library sys:

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 exit is made at the expense of an exception System.Exit, as you can see in the documentation, which allows the program to perform cleaning actions. The parameter 0 past indicates that the program ended successfully.

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

  • Shoooow^^ - 0-o

Browser other questions tagged

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