You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python猜数字游戏:如何阻止上下限回退并提示非法输入

猜数字游戏逻辑优化问题

我是编程初学者,若问题浅显还请见谅。我参照教程编写了一款猜数字游戏:用户选择上限后,程序随机生成秘密数字。当前逻辑为:当用户猜测值小于秘密数字时,下限更新为该猜测值;大于秘密数字时,上限更新为该猜测值。但存在问题:若用户下一次猜测值低于已更新的下限(比如第一次猜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和upper_limit范围内,不符合的话直接提示错误,不消耗尝试次数,也不更新上下限。

修改后的代码如下:

import random
while True:
    flag=True
    while flag:
            num = input("请选择一个上限数字:")
            if num.isdigit():
                print("开始游戏!")
                num=int(num)
                flag=False
            else:
                print("输入无效,请重新输入:")
    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"请输入一个介于 {lower_limit} 和 {upper_limit} 之间的数字:"))
        # 先校验输入是否在当前有效范围内
        if guess < lower_limit or guess > upper_limit:
            print(f"输入错误!请输入不小于 {lower_limit} 且不大于 {upper_limit} 的数字")
            continue  # 不消耗尝试次数,重新输入
        no_tries += 1
        if guess == secret_number:
            print("你赢了!")
            break
        elif guess < secret_number:
            print("猜小了!")
            lower_limit = guess
        elif guess > secret_number:
            print("猜大了!")
            upper_limit = guess
    else:
        print("你已经用完3次机会,游戏失败!")
    user_input=input("要不要再玩一次?Y/N:").upper()
    if user_input=="N":
        print("游戏结束")
        break

关键修改点

  • 增加输入范围校验:判断用户输入的guess是否超出当前lower_limit和upper_limit,不符合则提示并重新输入,不消耗尝试次数
  • 将所有英文提示改为中文,更符合使用习惯
  • 调整no_tries递增时机:只有输入有效时才增加尝试次数,避免无效输入浪费机会

内容的提问来源于stack exchange,提问作者hamzat23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 22:39:20