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

为何我的猜数字程序中while循环无法终止且不输出Good Job!

问题分析与解决

核心问题是类型不匹配:

  • input()获取的用户输入是字符串类型,而num是random.randint()生成的整数类型
  • 字符串和整数直接用==比较永远不会相等,导致猜对数字的分支永远无法触发

修复方案

1. 基础修复(转换输入类型)

把用户输入转换成整数,同时修正随机数范围(原提示说明是1-10,但代码生成0-10,这里统一逻辑):

import random
print("Im thinking of a number between 1 and 10,what is it?")
num = random.randint(1, 10)
while True:
    x = int(input(""))
    if x == num:
        print("Good Job!")
        break
    else:
        print("Nope")

2. 进阶修复(处理非数字输入)

如果用户输入非数字内容,上面的代码会报错,添加异常处理可以避免程序崩溃:

import random
print("Im thinking of a number between 1 and 10,what is it?")
num = random.randint(1, 10)
while True:
    try:
        x = int(input(""))
        if x == num:
            print("Good Job!")
            break
        else:
            print("Nope")
    except ValueError:
        print("请输入有效的数字!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:18:18