繁体   English   中英

收到有效输入后,如何中断用户选择的循环?

[英]How to break loop to user's choice once valid input is received?

如果用户没有选择 1 或 2,我希望代码说“请输入 1 或 2 以继续”,该部分有效。 但是,如果用户输入“6”,它会询问“请输入 1 或 2 以继续”,但如果在无效输入后直接输入有效输入,则代码无法正确显示。

我试图在没有需求功能的情况下做到这一点,但似乎没有任何我想要的方式工作。

def requirement():
    choice = ""
    while choice != "1" and choice != "2":
        choice = input ("Please enter 1 or 2 to continue.\n")
    if choice == "1" and choice == "2":
        return choice

def intro():
    print ("Enter 1 to enter the cave\n")
    print ("Enter 2 to explore the river\n")

    play_again = input ("What would you like to do?\n")
    if play_again in "1":
        print ("You win!")
    elif play_again in "2":
        print ("YOU LOSE")
        print ("Thanks for playing!")
        exit()
    else:
        requirement()
intro()
def intro():
    print ("Enter 1 to enter the cave\n")
    print ("Enter 2 to explore the river\n")
    play_again = input ("What would you like to do?\n")
    return play_again

def game(choice):
    if choice == "1":
        print ("You win!")
    elif choice == "2":
        print ("YOU LOSE")
        print ("Thanks for playing!")
        exit()
    else:
        choice = input ("Please enter 1 or 2 to continue.\n")
        game(choice)

game(intro())

else语句已经处理了是否输入 1 或 2,因此不需要requirement函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM