1

我正在为 Zed Shaw 努力学习 python,我正在练习 36。他希望我们制作一个类似于 ex 35 的游戏。这是我的代码的一部分。

def ninja_dojo():
    print """
    You enter a big room.
    A ninja sits meditating between you and a door.
    How do you get past the ninja?
    """
    pass_ninja = False

    while True:

        move = raw_input('> ')

        if move == 'walk quietly':
            dead("As you pass the ninja, he springs up and guts you.")

        elif move == 'greet ninja':
            print "The ninja smiles and motions for you to pass."
            arcade()

        elif move == 'fight ninja':
            dead("As you step forward to make your move, the ninja throws a Shuriken               that slits your throat. You slowly bleed out.")

        else:
            dead("The ninja notices you and kills you, thinking you're an intruder. ooops.")
            exit(0)

当我运行它并传递满足 else 块的东西时,我得到了这个错误。

Traceback (most recent call last):   File "/Users/Anusha/Desktop/Anusha/Freshmore/Python/ex1.py", line 834, in <module>
    start()   File "/Users/Anusha/Desktop/Anusha/Freshmore/Python/ex1.py", line 829, in start
    ninja_dojo()   File "/Users/Anusha/Desktop/Anusha/Freshmore/Python/ex1.py", line 807, in ninja_dojo
    exit(0) SystemExit: 0

谁可以给我解释一下这个?为什么 exit(0) 在这里不起作用?这是 Zed 的代码,它工作得很好。

  def gold_room():
    print "This room is full of gold.  How much do you take?"

    next = raw_input("> ")

    if "0" in next or "1" in next:
        how_much = int(next)

    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("Your greedy bastard!")

我已经用“from sys import exit:就像他一样开始了我的模块。对于我的while循环,如果我使用break代替exit(0),它可以完美地工作。我的问题是为什么exit(0)不起作用?提前致谢!

4

2 回答 2

1

sys.exit()通过引发SystemExit异常来工作。如果有任何东西捕捉到它或祖先,那么异常处理程序将运行。

于 2013-10-15T11:48:06.823 回答
0

sys.exit(code)引发SystemExit异常。如果你想退出,你可以使用breakreturn

于 2013-10-15T11:47:54.273 回答