2013-10-15 39 views
1

我正在研究Zed Shaw的Python學習方法,我在練習36上。他希望我們製作一個類似於前35的遊戲。這是我的代碼。while循環中的sys.exit()函數

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 

有人可以向我解釋這一點嗎?爲什麼不退出(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!") 

我開始我的「模塊從SYS進口出口:就像他 對於我while循環,如果我在的地方退出使用break(0),它完美的作品我的問題是,爲什麼沒有按。 「T退出(0)工作? 由於一噸提前!

+1

以何種方式無效?似乎完全按照你的要求,提出異常退出程序。 –

回答

1

sys.exit()的作品。如果任何東西都會抓住它或祖先,那麼異常處理程序將運行。

+0

謝謝!當你說「異常處理程序將運行。」時,是我收到的錯誤信息? – user2882228

+0

它會,但我不熟悉應用程序或解釋器,會產生該格式的回溯。 –

+0

哦,好的。我正在使用IDLE – user2882228

0

sys.exit(code)引發SystemExit例外。如果你想退出,可以通過提高SystemExit異常使用breakreturn