How to use sys.exit() in Python


player_input = '' # This has to be initialized for the loop

while player_input != 0:

    player_input = str(input('Roll or quit (r or q)'))

    if player_input == q: # This will break the loop if the player decides to quit

        print("Now let's see if I can beat your score of", player)

    if player_input != r:

        print('invalid choice, try again')

    if player_input ==r:

        roll= randint (1,8)

        player +=roll #(+= sign helps to keep track of score)

        print('You rolled is ' + str(roll))

        if roll ==1:

            print('You Lose :)')



I am trying to tell the program to exit if roll == 1 but nothing is happening and it just gives me an error message when I try to use sys.exit()

This is the message that it shows when I run the program:

Traceback (most recent call last):
 line 33, in <module>

This question is tagged with python python-3.x exit

~ Asked on 2013-02-01 03:07:47

The Best Answer is


I think you can use


You may check it here in the python 2.7 doc:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

~ Answered on 2017-03-03 12:36:12


sys.exit() raises a SystemExit exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit

~ Answered on 2013-02-01 03:09:51

Most Viewed Questions: