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

Python编写的猜数字程序出现无限循环问题该如何解决?

问题原因及修复方案

你的程序出现异常是由两个逻辑漏洞共同导致的,具体如下:

  • 缺少循环内的猜测值更新逻辑
    你仅在循环外执行了一次input读取用户的猜测值,只要第一次输入的数值没有猜中,guess_number的取值就永远不会变化,while secret_number != guess_number的判断条件会永远为真,直接触发无限循环。
  • 缺少生命值耗尽的终止判断
    当前循环没有把「生命值归0」作为终止条件,哪怕lives被扣到负数,程序也不会主动停止运行。由于Python循环执行速度极快,只要进入无限循环就会瞬间扣完6点生命值,这就是你看到快速耗尽生命提示的原因。

修复后的可运行代码

import random
secret_number = random.randint(1, 100)
lives = 6

while lives > 0:
    guess_number = int(input('What is your guess?'))
    if secret_number > guess_number:
        print('Try higher')
        lives -= 1
    elif secret_number < guess_number:
        print('Try lower')
        lives -= 1
    else:
        print('You guessed the number!')
        break

# 可选:增加游戏结束提示
if lives == 0:
    print(f'Game over! The correct number is {secret_number}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:27:00