我已添加此功能,确保用户确实想要退出该程序。当你真的想要退出时它可以工作,但如果你想返回程序,它只是循环语句:
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 ')
答案 0 :(得分:5)
将print ('')
替换为sys.exit (0)
并删除return WantToQuit()
。
我还建议您在.lower()
变量上应用Quit
,以便它不区分大小写。
答案 1 :(得分: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
函数返回一个布尔值,无论用户实际是否想要退出。如果是这样,那么无限循环就会被打破,程序会自然退出。
第二个示例处理WantToQuit
函数内部的退出,调用sys.exit()
立即退出。
第一种可能更可取,尽管两者都在实践中使用。
答案 2 :(得分:0)
您可以使用名为quit()
的已定义函数,而不是创建新函数。 quit
功能会弹出一个框,上面写着:
[In]
quit()
[OUT]
Your program is still running!
Do you want to kill it?
Yes No