首页 > 解决方案 > 一旦收到有效输入,如何打破用户选择的循环?

问题描述

如果用户没有选择 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()

标签: pythonpython-3.x

解决方案


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函数。


推荐阅读