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

Python猜数字游戏bug排查:猜对数字仍提示错误

Python猜数字游戏:猜对后仍提示错误的问题排查与修复

你的代码里有几个关键问题导致猜对数字仍提示错误,逐个排查如下:

  • 类型不匹配(核心问题):input()获取的用户输入是字符串类型,而random.randint(1,10)生成的是整数。直接用==比较字符串和整数永远不会相等,所以哪怕你输入的数字和目标一致,程序也会判定错误。解决方法是把用户输入转换成整数,比如guess1 = int(input('Your first guess: '))。

  • 逻辑结构错误:当前代码中,第一次猜完后,不管对错,后续的if guess2 == number都会执行。如果第一次猜对了,guess2根本没定义,会直接抛出NameError。需要把后续的猜数步骤嵌套在else块里,确保只有前一次猜错时才执行下一次猜数。

  • 条件判断语法错误:if input2 == 'Yes' or 'yes' 这种写法逻辑不对,Python会把'yes'当成布尔值True,所以这个条件永远为真。正确写法应该是if input2.lower() == 'yes'(统一转小写后判断,更简洁),或者if input2 == 'Yes' or input2 == 'yes'。

  • 冗余导入与不必要的函数:from fileinput import close完全没用,Python程序结束时会自动释放资源,不需要手动调用close();另外重复导入了random模块,只需要在开头导入一次即可。

  • 缩进错误:代码最后的else: close() repeat()缩进完全错误,导致逻辑混乱,需要把这些代码放在对应的if块的else分支里。


修正后的完整代码

import random

def repeat():
    number = random.randint(1, 10)
    # 测试用可以保留下面的print,正式玩时注释掉即可
    # print(number)
    
    # 第一次猜数,处理非整数输入
    try:
        guess1 = int(input('Your first guess: '))
    except ValueError:
        print("请输入有效的整数!")
        repeat()
        return
        
    if guess1 == number:
        print('You are correct! You only needed one try!')
    else:
        print('Wrong, two tries left!')
        # 第二次猜数
        try:
            guess2 = int(input('Your second guess: '))
        except ValueError:
            print("请输入有效的整数!")
            repeat()
            return
            
        if guess2 == number:
            print('You are correct! You needed two tries!')
        else:
            print('Wrong, one try left!')
            # 第三次猜数
            try:
                guess3 = int(input('Your third and last guess: '))
            except ValueError:
                print("请输入有效的整数!")
                repeat()
                return
                
            if guess3 == number:
                print('You are correct! It took you all three tries!')
            else:
                print(f'You are wrong! You lost! The number was: {number}')
                input2 = input('Do you want to play again? Yes or No? ')
                if input2.lower() == 'yes':
                    repeat()
                else:
                    print("游戏结束!")

# 启动游戏流程
print('Do you want to play a game?')
input1 = input("yes or no? ")
if input1.lower() == "yes":
    print("You have 3 tries to guess a random integer between 1-10. If you guess right you win. If not I do. Ready?")
    repeat()
else:
    print("游戏结束!")

额外优化说明:

  • 增加了try-except块处理用户输入非整数的情况,避免程序崩溃
  • 修正了原提示中“0-10”和代码实际生成“1-10”的不一致问题
  • 优化了提示语的标点,让逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:35:24