如何在Python中使用sys.exit()

use*_*690 16 python exit python-3.x

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)
        break

    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 :)')

            sys.exit

            break
Run Code Online (Sandbox Code Playgroud)

我试图告诉程序退出,roll == 1但没有发生任何事情,它只是给我一个错误消息,当我尝试使用sys.exit()


这是我运行程序时显示的消息:

Traceback (most recent call last):
 line 33, in <module>
    sys.exit()
SystemExit
Run Code Online (Sandbox Code Playgroud)

god*_*ier 18

我想你可以用

sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

你可以检查它这里在Python 2.7 DOC:

可选参数arg可以是一个整数,给出退出状态(默认为零)或其他类型的对象.如果它是整数,则零被认为是"成功终止",并且任何非零值被贝壳等视为"异常终止".


Ped*_*tes 10

您没有在代码中导入 sys,也没有在调用函数时关闭 ()...尝试:

import sys
sys.exit()
Run Code Online (Sandbox Code Playgroud)


Abh*_*jit 5

sys.exit()引发一个SystemExit异常,你可能会认为这是一个错误.如果您希望程序不提升SystemExit但正常返回,则可以将功能包装在函数中并从计划使用的位置返回sys.exit