错误信息 TypeError: 不支持'int'和'module'之间的 '<' 运算

0 投票
1 回答
30 浏览
提问于 2025-04-13 00:15
""" 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 that gets the number
      the player has to guess and then returns a random number
      between 1 and 10
"""
def play_game():
  random=random.randint(1,10)

"""While statement so the user can guess the number until the
     the guess is correct
"""
while True:
  guess=int(input('Enter a number between 1 and 10   '))
  
  
  if guess < random:
      print('Too low')

  elif guess > random:
      print('Too high')

  else:
        print('You guessed it')

我尝试过调整间距,但我觉得这个错误不是因为间距造成的。
我希望代码能够正常运行,没有错误。

1 个回答

0

首先,别把变量和模块用同样的名字。这样会让人困惑,正如你看到的那样。在这个例子中,你导入了 random 模块,同时又把它当作一个局部变量的名字:

def play_game():
  random=random.randint(1,10)

random 赋值给一个局部变量,这样就覆盖了 random 模块。所以当你尝试执行 random.randint(1,10) 时,它实际上是在用一个未定义的变量 random,这当然会报错。所以最好换个名字,比如:

def play_game():
  rand_val=random.randint(1,10)

这样可以解决部分问题。但另一个问题是,即使这样修复了,rand_val 仍然只在 play_game 函数内部可用,外面无法访问。更好的做法是让 play_game 返回这个值,但如果你真的想用全局变量,那就需要声明它为全局变量,比如:

def play_game():
  global rand_val
  rand_val=random.randint(1,10)

这样做后,你就可以在其他函数中访问 rand_val(前提是先调用过 play_game)。

当然,你还需要实际调用 play_game(),而你现在并没有这样做。

下面是一个完整的解决方案。我没有包括标题代码,因为它和这个问题无关:

import random


def play_game():
    global rand_val
    rand_val=random.randint(1,10)


play_game()

while True:
    guess=int(input('Enter a number between 1 and 10   '))

    if guess < rand_val:
        print('Too low')

    elif guess > rand_val:
        print('Too high')

    else:
        print('You guessed it')
        break

这样是可以的。一旦猜对了数字,就会退出循环。

顺便说一下,把 play_game 函数设计成真正进行游戏可能更合理,也就是说把游戏循环放到那里。这样还可以消除全局变量(它可以是局部的)。

撰写回答