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

Python实现电脑猜心数字游戏 代码错误排查求助

猜数字程序运行异常排查

我是编程新手,尝试编写一款猜数字程序:我在心中默想一个1-99区间内的数字,由电脑持续猜测该数字,直到我确认猜对为止。
程序交互规则如下:

  • 电脑在当前有效猜测范围内随机生成数字并展示
  • 若猜测结果正确,我输入c确认
  • 若我心中的数字小于电脑的猜测值,输入s缩小猜测范围
  • 若我心中的数字大于电脑的猜测值,输入b缩小猜测范围,降低电脑后续的猜测难度

我编写了对应实现代码,但运行时存在异常,无法定位错误位置,原代码如下:

import random
first=1
second=99
guess=random.randint(first,second)
print(guess)
answer=input("what is the number in your head(don't enter it, just compare it with the number on the screen)? print c for correct, b for bigger and s for smaller! \n")
while answer!="c":
    if answer=="b":
        first==guess+1
        guess=random.randint(first,second)
        print(guess)
    elif answer=="s":
        second==guess-1
        guess=random.randint(first,second)
        print(guess)
answer=input("what do you think about the new number? ")
print("you did it!")

代码核心错误

  1. 赋值运算符误用:更新猜测上下界的时候用了双等号==,这是相等判断运算符,不会修改first和second的变量值,应该用单等号=做赋值。这个错误会导致猜测范围永远锁死在1-99,电脑不会根据反馈缩小范围。
  2. 循环缩进错误:读取用户新输入的answer=input(...)语句被放在了while循环外部,第一次输入如果不是c,循环内部不会读取后续输入的指令,会陷入死循环反复打印同一个猜测值。

修正后可运行代码

import random
first = 1
second = 99
guess = random.randint(first, second)
print(guess)
answer = input("请对照你心里的数字判断:猜对输入c,你心里的数字更大输入b,更小输入s:\n")
while answer != "c":
    if answer == "b":
        first = guess + 1
        guess = random.randint(first, second)
        print(guess)
    elif answer == "s":
        second = guess - 1
        guess = random.randint(first, second)
        print(guess)
    # 把输入读取移到循环内部,每次猜完等待新指令
    answer = input("请对照新的猜测值输入指令:")
print("猜对了!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 13:27:25