【问题标题】:How do I get back to the top of a while loop?如何回到 while 循环的顶部?
【发布时间】:2021-08-17 08:07:49
【问题描述】:

所以我正在尝试自己做一个猜谜游戏,当游戏结束时,我希望它会提示玩家是否想再次玩,这样输入是或否:

Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) y
Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) n
Thank you for playing!

我设法让游戏正常运行,但我无法再次玩游戏。我被困在这里:

guess = int(input("Guess a number between 1 and 10: "))
while True:
    if guess > num:
        print("Too high, try again!")
        guess = int(input("Guess a number between 1 and 10: "))
    elif guess < num:
        print("Too low, try again!")
        guess = int(input("Guess a number between 1 and 10: "))
    else:
        print("You guessed it! You won!")
        replay = input("Do you want to continue playing? (y/n) ")
        if replay == "y":
            **what to insert here???**
        else:
            break

我不知道在 if 语句中输入什么内容,如果用户按“y”并允许我重新开始游戏,我的代码将返回到循环顶部。

任何帮助将不胜感激!请不要给我整个解决方案,而是尝试给我提示,以便我自己解决这个问题!谢谢!

【问题讨论】:

    标签: python-3.x if-statement while-loop conditional-statements


    【解决方案1】:

    您必须使用两个 while 循环。第一个决定玩家是否想再玩一次,第二个是从用户那里得到猜测,直到用户猜对为止。

    while True:
        guess = int(input("Guess a number between 1 and 10: "))
        wantToPlay = False
        while True:
            if guess > num:
                print("Too high, try again!")
                guess = int(input("Guess a number between 1 and 10: "))
            elif guess < num:
                print("Too low, try again!")
                guess = int(input("Guess a number between 1 and 10: "))
            else:
                print("You guessed it! You won!")
                replay = input("Do you want to continue playing? (y/n) ")
                if replay == "y":
                    wantToPlay = True
                else:
                    break
        if wantToPlay == False:
            break
    

    【讨论】:

    • 引用问题:“请不要给我完整的解决方案,而是尝试给我提示,以便我自己解决这个问题”。一个 while True 外观将条件 break 作为最后一条语句进行重构。
    【解决方案2】:

    您可以使用 continue 语句,因为它将控制返回到 Python 中的 while 循环的开头。

    【讨论】:

    • 你用代码试过你的建议了吗?代码现在是否具有预期的行为?
    猜你喜欢
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2016-07-12
    • 2019-07-03
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多