如果没有更多代码,很难向您展示您做错了什么,但我认为您的设置如下:
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()
立即退出。
第一个可能更可取,尽管两者都在实践中使用。