user3503822
user3503822

Reputation: 11

Get python to end the program in an if statement

I am creating a game style program and are looking for a command that will just end the program at a certain point. There are no syntax errors and it all correctly indented in the idle.

I want this command to execute after the 'YOU DIED GAME OVER' bit of the if statment. I tried to look for anything online but i couldn't find any hints. Code below

buy2a = input ('Type Y to drink the strange liquid and type N not to')
if buy2a == 'Y' or buy2a == 'y':
    chance2a = 2 #random.randint(1,4)
    if chance2a == '2' or chance2a == '4' :
      print ('You start to choke and you black out')
      print ('YOU DIED')
      print ('GAME OVER')
      # >Thing im looking for goes here!<#
else :
    print ('You feel strange')
    time.sleep(1)
    print ('You blackout but wake up several hours later')
    time.sleep(1)
    health = 20
    print ('You feel a lot better and now have ' + str(health) + ' health')

else :
    print ('You pass on the offer with a weak reason and head off in a hurry')
print ('You enter the next town on weiry feet')

Upvotes: 1

Views: 1026

Answers (3)

Eric
Eric

Reputation: 97681

You can also raise the exception directly

raise SystemExit()

Upvotes: 0

vaultah
vaultah

Reputation: 46593

Built-in exit() function will work. Another option is to use sys.exit.

Both sys.exit and exit raise the same exception SystemExit. The difference is in convenience: you need to import sys module every time you want to use sys.exit and exit is the part of site module that's imported during the initialization.

Upvotes: 1

anon582847382
anon582847382

Reputation: 20391

Use (this is standard practice for exiting):

import sys  # At the start of file.
sys.exit()  # When you want to exit.

Upvotes: 4

Related Questions