1

私はZed Shawのlearn python the hard wayに取り組んでいて、私はExercise 36に取り組んでいます.

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: just like him.」でモジュールを開始しました。私の while ループでは、exit(0) の代わりに break を使用すると、完全に機能します。私の質問は、なぜ exit(0) が機能しないのですか?よろしくお願いします!

4

2 に答える 2

1

sys.exit()SystemExit例外を発生させることで機能します。何かがそれまたは祖先をキャッチすると、例外ハンドラーが実行されます。

于 2013-10-15T11:48:06.823 に答える
0

sys.exit(code)例外を発生させSystemExitます。終了したい場合は、breakまたはを使用できますreturn

于 2013-10-15T11:47:54.273 に答える