很难向你展示你做错了没有更多的代码是什么,但在这里就是我的身影,你把它设置:
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()
立即退出。
第一个可能是可取的,虽然两者都在实践中使用。
是否有你'WantToQuit()'函数来调用一个理由本身递归? – 2013-03-22 10:26:41
你应该真的缩进你的代码,所以我们至少可以知道返回语句或第二个raw_input属于哪里 – 2013-03-22 10:26:47
我刚才意识到我调用了它两次,我应该返回什么函数? – user1655562 2013-03-22 10:28:24