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

Python3猜数字游戏判断逻辑异常 输入提示错误问题排查求解

Python3猜数字游戏逻辑错误修复

异常复现

  • 预设待猜值为90时,首次输入100可正常提示数值过高,但后续输入8作为新猜测值,程序仍错误提示数值过高
  • 输入值等于正确答案90时,程序依旧返回数值过高的提示,无法进入猜中分支

问题代码

number_guess = int(input("Enter the integer for the player to guess:"))
user_guess = int(input("Enter your guess."))
count = 1
while user_guess != number_guess:
    count += 1
    if user_guess == number_guess:
        print("You guessed it in", count, "tries")
    elif user_guess < number_guess:
        int(input("Too low - try again:"))
    elif user_guess > number_guess:
        int(input("Too high - try again:"))

问题根因

  • 没有更新存储猜测值的变量:循环内的高低判断分支接收用户新输入时,只做了int()类型转换,没把新输入的值重新赋值给user_guess。第一次输入100之后,user_guess的值就永远停在100了,后面不管输入8还是90,程序判断时拿的还是最开始的100,自然会一直提示猜大了。
  • 猜中分支放错了位置:猜中成功的打印逻辑写在了while循环内部,但这个while循环只有在user_guess不等于正确答案的时候才会执行,一旦真的输入了正确答案,循环直接跳过不进,那段猜中提示永远跑不到。
  • 计数逻辑错位:一进循环先给猜测次数+1,没有和实际用户输入动作绑定,就算逻辑跑通,最后统计的猜测次数也会出错。

修复后可运行代码

number_guess = int(input("请设置待猜测的整数:"))
count = 0
while True:
    user_guess = int(input("请输入你的猜测值:"))
    count += 1
    if user_guess == number_guess:
        print(f"恭喜你猜中了!总共尝试了{count}次")
        break
    elif user_guess < number_guess:
        print("猜小了,再试一次:")
    else:
        print("猜大了,再试一次:")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:48:16