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

Python猜数字游戏函数异常排查与优化请求

机器猜数字游戏函数问题修复与优化建议

问题描述

我正在提升Python技能,编写了一个机器猜数字的游戏函数,但运行出现异常:首次输入1(表示猜中)后,程序重复显示输入提示语句再输出恭喜信息,而非直接提示成功。

错误输出:

We will play a guess game.
Is this 50 your number?
0 means too low, 1 this is the number and 2 means too high 1
0 means too low, 1 this is the number and 2 means too high 1
Congrats ! You guess after 1 tries

原函数代码:

def guess_game():
    m = 50
    count = 0
    print('We will play a guess game.')
    print('Is this ' + str(m) + ' your number?')
    myinput = input('0 means too low, 1 this is the number and 2 means too high')
    while myinput != 1:
        myinput = input('0 means too low, 1 this is the number and 2 means too high')
        count += 1
        if myinput == '0':
            print('Not the right one. Too low')
            for m in range(m,m+1):
                m += 1
            print('Is this ' + str(m) + ' your number?')
        elif myinput == '2':
            print('Not the right one. Too high.')
            for m in range(m,m+1):
                m -= 1
            print('Is this ' + str(m) + ' your number?')
        else: 
            print('Congrats ! You guess after ' + str(count) + ' tries')
            break

问题根源

  1. 类型不匹配:input()返回的是字符串,而循环条件判断的是myinput != 1(整数),导致第一次输入'1'时,字符串'1'不等于整数1,循环会继续执行,所以会再次弹出输入提示。
  2. 冗余代码:用for m in range(m,m+1)来修改m完全没必要,直接m +=1或m -=1即可。
  3. 计数逻辑错误:首次猜中时,count被额外加了1,但这实际上是第一次尝试,计数时机不对。

修复后的代码

def guess_game():
    m = 50
    count = 1  # 第一次猜就算一次尝试
    print('We will play a guess game.')
    print(f'Is this {m} your number?')
    
    while True:
        try:
            myinput = int(input('0 means too low, 1 this is the number and 2 means too high: '))
        except ValueError:
            print('请输入0、1或2中的一个数字!')
            continue
            
        if myinput == 1:
            print(f'Congrats ! You guessed right after {count} tries')
            break
        elif myinput == 0:
            print('Not the right one. Too low')
            m += 1
            print(f'Is this {m} your number?')
            count += 1
        elif myinput == 2:
            print('Not the right one. Too high.')
            m -= 1
            print(f'Is this {m} your number?')
            count += 1
        else:
            print('请输入0、1或2中的一个数字!')

优化建议

  • 改用二分法猜数:不要每次只±1,而是维护一个猜数范围(比如1-100),每次取中间值,大幅减少猜测次数。示例:
    def guess_game():
        low = 1
        high = 100
        count = 0
        print('请想一个1到100之间的数字,我来猜!')
        
        while low <= high:
            count += 1
            m = (low + high) // 2
            print(f'Is this {m} your number?')
            
            try:
              myinput = int(input('0 means too low, 1 this is the number and 2 means too high: '))
            except ValueError:
                print('请输入0、1或2!')
                count -=1  # 无效输入不计入次数
                continue
                
            if myinput == 1:
                print(f'恭喜!我用了{count}次猜中了!')
                return
            elif myinput == 0:
                low = m + 1
            elif myinput == 2:
                high = m - 1
            else:
                print('请输入0、1或2!')
                count -=1
        print('你是不是作弊了?我找不到这个数字!')
    
  • 使用f-string格式化字符串:比str()拼接更简洁易读。
  • 增加输入验证:捕获非数字输入,提示用户正确输入,避免程序崩溃。
  • 明确猜数范围:给用户明确的数字范围,比如1-100,让游戏规则更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:55:19