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

Python猜数字游戏报TypeError:int与module无法比较,求修复

修复Python猜数字游戏的TypeError问题

错误原因分析

你遇到的TypeError: '<' not supported between instances of 'int' and 'module'源于两个核心问题:

  • 变量名冲突:在play_game函数里用random作为变量名,覆盖了导入的random模块,但这个变量是函数局部变量,外部while循环里的random仍然是模块对象,导致整数和模块对比时出错。
  • 代码结构混乱:play_game函数定义后未执行,且while循环缩进位置错误,没有和生成随机数的逻辑关联。

修复后的完整代码

"""Random module that defines a series of functions
for generating or manipulating random integers
"""
import random


"""Function to display the title and programming
specifications of the project
"""
def display_title(name, specifications):
    print(name + specifications)

display_title('The game is called Guessing game\n',
              'The rules are simple: Pick a number between 1 and 10\n')

"""Function that uses the randint() function to generate
the number the player has to guess
"""
def play_game():
    # 更换变量名,避免覆盖random模块
    secret_number = random.randint(1, 10)
    while True:
        guess = int(input('Enter a number between 1 and 10   '))
        
        if guess < secret_number:
            print('Too low')
        elif guess > secret_number:
            print('Too high')
        else:
            print('You guessed it!')
            # 猜对后退出循环,避免无限输入
            break

# 调用游戏函数启动游戏
play_game()

关键修复点

  • 重命名变量:将函数内的随机数变量从random改为secret_number,彻底避免和模块名冲突。
  • 调整代码结构:把while循环缩进放入play_game函数内,确保使用的是函数内生成的目标随机数。
  • 添加退出逻辑:猜对后用break终止循环,结束游戏流程。
  • 优化格式:调整部分空格、标点,让代码更易读规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:16:02