首页 文章

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

提问于
浏览
9
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

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


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

Traceback (most recent call last):
 line 33, in <module>
    sys.exit()
SystemExit

3 回答

  • 0

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

  • 8

    我想你可以用

    sys.exit(0)
    

    你可以在python 2.7 doc中检查它here

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

  • 5

    使用2.7:

    from functools import partial
    from random import randint
    
    for roll in iter(partial(randint, 1, 8), 1):
        print 'you rolled: {}'.format(roll)
    print 'oops you rolled a 1!'
    
    you rolled: 7
    you rolled: 7
    you rolled: 8
    you rolled: 6
    you rolled: 8
    you rolled: 5
    oops you rolled a 1!
    

    然后将"oops"打印更改为 raise SystemExit

相关问题