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

时间:2019-07-10 15:52:06

标签: python python-3.x

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

1 个答案:

答案 0 :(得分:0)

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