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

运行猜数字Python代码时陷入无限循环,输出“Higher”求助

猜数字代码无限循环问题修复

你的代码存在几个关键问题导致无限循环:

  • 初始guess值无效:guess = int(float())是错误写法,会让guess初始为0,且没有关联用户的第一次输入,循环中也没更新这个值,导致循环条件永远满足。
  • 循环逻辑缩进错误:更新guess和tries的代码被放在了while循环外面,循环内部完全没有修改guess的值,自然会无限输出"Higher"或"Lower"。
  • 输入处理冗余:第一次输入的question变量没有赋值给guess,等于白拿了用户输入。
  • 字符串语法错误:print和结尾input的字符串存在未正确处理的换行和引号问题,会触发语法报错。

修复后的代码如下:

# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low or right on the money

import random

# 打印游戏说明
print("This is guess my number\nI'm thinking of a number between 0-100")

def ask_number():
    """Ask for a number within a range."""
    the_number = random.randint(1, 100)
    # 获取用户第一次猜测
    guess = int(input("Take a guess: "))
    tries = 1

    while guess != the_number:
        if guess < the_number:
            print("Higher...")
        else:
            print("Lower...")
        # 在循环内更新猜测和次数
        guess = int(input("Try again: "))
        tries += 1 

    # 循环结束说明猜对了
    print(f"Well done, the number was {the_number}")
    print(f"It took you {tries} attempt/s")

ask_number()

input("\nPress enter key to exit")

修复说明:

  1. 去掉无效的初始guess赋值,直接获取用户第一次输入作为初始guess。
  2. 将guess = int(input(...))和tries +=1移到while循环内部,确保每次循环都更新猜测值,让循环能正常结束。
  3. 简化输入处理,直接把用户输入赋值给guess,去掉冗余的question变量。
  4. 修正字符串的换行和引号问题,确保语法正确。
  5. 使用f-string让输出更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:55:02