2013-10-15 40 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