26
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
4

6 回答 6

28

我认为你可以使用

sys.exit(0)

您可以在 python 2.7 文档中查看

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

于 2017-03-03T12:36:12.037 回答
8

sys.exit()引发一个SystemExit异常,您可能认为它是一些错误。如果您希望您的程序不引发 SystemExit 而是优雅地返回,您可以将您的功能包装在一个函数中并从您计划使用的地方返回sys.exit

于 2013-02-01T03:09:51.443 回答
5

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

import sys
sys.exit()
于 2019-09-10T15:47:39.687 回答
2

使用 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

于 2013-02-01T03:20:58.530 回答
2

与 Pedro Fontez 所说的一些回复一致,您似乎最初从未调用 sys 模块,也没有设法在 sys.exit 末尾粘贴 required ():

所以:

import sys

完成后:

sys.exit()
于 2020-08-31T17:07:22.913 回答
0

真实世界的例子

选项1:sys.exit()

退出 Python 并引发 SystemExit 异常。

import sys
try:
  sys.exit("This is an exit!")
except SystemExit as message:
  print(message)

输出:

This is an exit!

选项 2:sys.exit()

退出 Python 而不显示消息

import sys
sys.exit()

# runtime: 0.07s 
于 2022-02-14T16:13:16.623 回答