我的python再次播放功能不起作用

时间:2015-09-04 23:07:08

标签: python python-3.x

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,它将不会退出。该程序将在第三次再次问我这个问题,如果我按否,它将正确退出。

我知道解决方案可能非常明显,但我似乎无法修复它。

2 个答案:

答案 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()