How could I implement this code so that if I type "a" as 0 the program stops immediately and the message "END" appears?

Asked

Viewed 61 times

0

def conta(x,y,z):
     return (a**b)+c


a = int(input('Infome a: '))
if a == 0:
    print('FIM')
b = int(input('Infome b: '))
c = int(input('Infome c: '))

result = conta(a,b,c)
print(result)
  • Ignore the "N" at the end of the question...

  • stop in order to pause, or terminate the program? To terminate the program immediately you can invoke the function exit(0).

2 answers

3

Add an Else. Your code will look like this:

def conta(x,y,z): 
    return (a**b)+c

a = int(input('Infome a: ')) 
if a == 0: 
    print('FIM')
else:
    b = int(input('Infome b: ')) 
    c = int(input('Infome c: '))
    
    result = conta(a,b,c) 
    print(result)

1


That way you can:

def conta(x,y,z):
     return (a**b)+c

a = int(input('Infome a: '))
if a != 0:
    b = int(input('Infome b: '))
    c = int(input('Infome c: '))
    result = conta(a,b,c)
    print(result)
else:
    print('FIM')

'I pulled the result = conta(a,b,c) and the print(result) into the if, hence they will only be executed if it is non-zero.

Code change as jsbueno suggested:

import sys

def conta(x,y,z):
     return (a**b)+c

a = int(input('Infome a: '))
if a != 0:
    b = int(input('Infome b: '))
    c = int(input('Infome c: '))
    result = conta(a,b,c)
    print(result)
else:
    print('FIM')
    sys.exit(0)

If you are using Anaconda you may present a message at the end of the execution.

  • 1

    This form is more elegant - but pegutna realemtne requires information that is missing there to be complete: to terminate a Python program at an arbitrary point it must be called sys.exit(0) (preceded by a import sys) - Can you add that to your reply? Then it’s complete for the next readers.

Browser other questions tagged

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