井字游戏-这是什么错误

时间:2020-06-19 03:42:34

标签: python

这里有什么错误?

Traceback (most recent call last)
<ipython-input-51-cb088c4c5c82> in <module>
     17             display_board(the_board)
     18             position = player_choice(the_board)
---> 19             place_marker(the_board,Player1_marker,position)
     20             if win_check(the_board,Player1_marker):
     21                 display_board(the_board)

<ipython-input-41-ba563e2cb168> in place_marker(board, marker, position)
      1 def place_marker(board, marker, position):
----> 2     board[position] = marker

TypeError: list indices must be integers or slices, not NoneType

1 个答案:

答案 0 :(得分:0)

显示的行准确地说明了哪里出问题了,在哪里。您只需要知道如何解释它即可:

     18             position = player_choice(the_board)
---> 19             place_marker(the_board,Player1_marker,position)

      1 def place_marker(board, marker, position):
----> 2     board[position] = marker

TypeError: list indices must be integers or slices, not NoneType

您可以从中得到的全部是:

  • position第2行中使用的place_marker()变量设置为None,因为这是 actual 错误(变量设置为None类型为NoneType,并且position是要投诉的列表索引);
  • 作为第19行对position的调用的一部分,place_marker()变量是从同名变量初始化的,因此也必须将其设置为None; < / li>
  • 该变量(传入的变量)来自函数player_choice()

换句话说,您的行:

position = player_choice(the_board)

由于某种原因返回了None

不幸的是,由于您没有向我们展示该函数的 code ,因此我们无法真正深入分析,但是您可能希望对于该函数中返回没有值的路径。这是函数返回None的典型原因,例如:

def fn(x):
    if x == 1:
        return 7 # This path returns 7 when 1 is passed in.
    # This path returns None (implicitly) for any other value.

print(fn(1)) # Explicitly gets 7.
print(fn(2)) # Implicitly gets None.

根据注释,运行该代码的结果是:

7
None