【问题标题】:In a Python guessing game, how do you stop the lower/upper limit from changing after it's already changed?在 Python 猜谜游戏中,如何阻止已经更改的下限/上限更改?
【发布时间】:2022-08-17 18:03:08
【问题描述】:

我是初学者,所以如果这是一个愚蠢的问题,请原谅我。我写了这个猜谜游戏(使用教程),用户选择一个上限,然后选择一个随机数作为“秘密数字”。

当用户猜测并且它低于/高于秘密数字时,下限/上限会改变以给用户一个提示。例如,密码为 50。用户输入 30。下限从 0 变为 30。

在下一次尝试中,如果用户键入低于 30 的数字,则下限会降低。例如,在第二次尝试中,用户写入 20。在第三次尝试中,下限现在为 20。

我不知道如何阻止这种情况发生。我希望程序告诉用户他们不能低于/高于他们在上一次尝试中猜测的数字,而不是改变下限。

这是代码:

import random
while True:
    flag=True
    while flag:
            num = input(\"Choose an upper bound: \")
            if num.isdigit():
                print(\"Let\'s play!\")
                num=int(num)
                flag=False
            else:
                print(\"Invalid input. Try again: \")
    secret_number = random.randint(1, num)
    no_tries=0
    max_tries=3
    lower_limit=0
    upper_limit=num ```

    while no_tries<max_tries:
        guess = int(input(f\"Please type a number between {lower_limit} and {upper_limit} \"))
        no_tries=no_tries+1
        if guess==secret_number:
            print(\"You won!\")
            break
        elif guess<secret_number:
            print(f\"You\'ve guessed wrong.\")
            lower_limit=guess
        elif guess>secret_number:
            print(f\"You\'ve guessed wrong.\")
            upper_limit=guess
    else:
        print(\"You have used all three tries. You lose!\")
    user_input=input(\"Would you like to play again? Y/N: \").upper()
    if user_input==\"N\":
        print(\"Game over\")
        break





  • 添加额外的比较。仅当lower_limit 小于guess 时才执行lower_limit=guess

标签: python


【解决方案1】:

在分配之前检查lower_limit 是否小于guess / upper_limit 是否大于guess

if guess == secret_number:
    print("You won!")
    break
elif guess < secret_number:
    if lower_limit < guess:
        print("You've guessed wrong.")
        lower_limit = guess
    else:
        print(f"You can't go lower than {lower_limit}!")
elif guess > secret_number:
    if upper_limit > guess:
        print("You've guessed wrong.")
        upper_limit = guess
    else:
        print(f"You can't go higher than {upper_limit}!")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多