def playAgain():
while True:
try:
replay = input("Do you want to play again? ").lower() #Asking user to play again
except ValueError:
print("Sorry, Invalid Entry") #If response invalid, will ask again
continue
if replay in ("yes","y","true","t"):
main()
elif replay in ("no","n","false","f"):
print ("Goodbye")
return
else: #If input is invalid will ask again
print("Invalid entry, Please enter yes or no")
def main():
print ("Hello")
playAgain()
main()
对于我的作业,我需要进行测验。我已经完成了所有工作接受再次播放功能,你可以在上面看到。我在退出该计划时遇到问题。如果我第一次输入时没有输入你想再次播放它会正确退出。我遇到的问题是,如果我第一次输入是,然后第二次输入no
,它将不会退出。该程序将在第三次再次问我这个问题,如果我按否,它将正确退出。
我知道解决方案可能非常明显,但我似乎无法修复它。
答案 0 :(得分:0)
在您的代码中,main
调用playAgain
。然后,如果您选择再次播放,playAgain
会递归调用main
。
main -> playAgain -> main -> playAgain
^^^
如果你return
在这里,只有第二个playAgain
退出,那么程序将返回到第一个playAgain
中的主循环。
要解决此问题,请在用户选择再次播放时添加return
以退出主循环:
if replay in ("yes","y","true","t"):
main()
return # here
答案 1 :(得分:0)
Python 2.7
:
def playAgain():
while True:
try:
replay = raw_input("Do you want to play again? ").lower() #Asking user to play again
if replay in ("yes","y","true","t"):
main()
return
elif replay in ("no","n","false","f"):
print ("Goodbye")
return
else: #If input is invalid will ask again
print("Invalid entry, Please enter yes or no")
except ValueError:
print("Sorry, Invalid Entry") #If response invalid, will ask again
def main():
print ("Hello")
playAgain()
main()