2013-03-22 103 views
0

我已经添加了这个功能,确保用户真的想退出程序。它的工作原理,当你真正想戒烟,但如果你想返回到程序,它只是循环语句:Python 2.7退出

def WantToQuit(): 
    Quit = raw_input("Please enter y if you are sure you want to quit, if not press n to return ") 
    if Quit == 'y': 
     print ('') 
    elif Quit == 'n': 
     DisplayMenu() 
     return WantToQuit() 

在别处:

elif Choice == 'q': 
    WantToQuit() 
    raw_input('Press enter key to continue ') 
+4

是否有你'WantToQuit()'函数来调用一个理由本身递归? – 2013-03-22 10:26:41

+2

你应该真的缩进你的代码,所以我们至少可以知道返回语句或第二个raw_input属于哪里 – 2013-03-22 10:26:47

+0

我刚才意识到我调用了它两次,我应该返回什么函数? – user1655562 2013-03-22 10:28:24

回答

5

更换print ('')sys.exit (0)与和删除return WantToQuit()

我也建议你在你的Quit变量上应用.lower(),这样它就不区分大小写。

1

很难向你展示你做错了没有更多的代码是什么,但在这里就是我的身影,你把它设置:

def WantToQuit(): 
    Quit = raw_input("Please enter y if you are sure you want to quit, if not press n to return ") 
    if Quit == 'y': 
     print ('') 
    elif Quit == 'n': 
     DisplayMenu() 
    return WantToQuit() 

while(True): 
    DisplayMenu() 
    # Some logic to get input and handle it 
    # For example, something like 
    selection = raw_input("Please make a selection: ") 
    if(selection == "1"): 
     doSomething() 
    elif(selection == "2"): 
     doSomethingElse() 
    elif(selection == "q"): 
     WantToQuit() 
    else: 
     # TODO: Handle this ! 
     pass 

这是我会怎么做:

def WantToQuit(): 
    Quit = raw_input("Please enter y if you are sure you want to quit, if not press n to return ") 
    if Quit == 'y': 
     return true 
    elif Quit == 'n': 
     return false 
    else: 
     # TODO: Handle this ! 
     pass 

while(True): 
    DisplayMenu() 
    # Some logic to get input and handle it 
    # For example, something like 
    selection = raw_input("Please make a selection: ").lower() 
    if(selection == "1"): 
     doSomething() 
    elif(selection == "2"): 
     doSomethingElse() 
    elif(selection == "q"): 
     if(WantToQuit()): break 
    else: 
     # TODO: Handle this ! 
     pass 

或者,你可以这样做:

def WantToQuit(): 
    Quit = raw_input("Please enter y if you are sure you want to quit, if not press n to return ") 
    if Quit == 'y': 
     sys.exit(0) 
    elif Quit == 'n': 
     return # Do nothing really 
    else: 
     # TODO: Handle this ! 
     pass 

while(True): 
    DisplayMenu() 
    # Some logic to get input and handle it 
    # For example, something like 
    selection = raw_input("Please make a selection: ").lower() 
    if(selection == "1"): 
     doSomething() 
    elif(selection == "2"): 
     doSomethingElse() 
    elif(selection == "q"): 
     WantToQuit() 
    else: 
     # TODO: Handle this ! 
     pass 

第一个例子有WantToQuit乐趣ction返回一个布尔值,无论用户实际上是想要退出。如果是这样,无限循环被破坏,程序自然退出。

第二个示例处理WantToQuit函数内的退出,并呼叫sys.exit()立即退出。

第一个可能是可取的,虽然两者都在实践中使用。

0

您可以使用已定义的函数quit()来代替新功能。该quit功能会弹出一个对话框,上面写着:

[在]

quit()

[OUT]

Your program is still running! 
Do you want to kill it? 
    Yes No