【问题标题】:Python Game | TypeError: argument of type 'NoneType' is not iterable蟒蛇游戏 | TypeError:“NoneType”类型的参数不可迭代
【发布时间】:2016-11-08 11:30:56
【问题描述】:

所以我正在阅读一本 Python 书籍,并被要求创建一个井字游戏并相对理解我所做的代码。到时候运行程序,我得到了这个奇怪的错误

TypeError: 'NoneType' 类型的参数不可迭代

完整的错误是:

Traceback (most recent call last):
   File "Tac Tac Toe Game revised.py", line 182, in <module>
     main()
   File "Tac Tac Toe Game revised.py", line 173, in main
     move = human_move(board, human)
   File "Tac Tac Toe Game revised.py", line 100, in human_move
     while move not in legal:
TypeError: argument of type 'NoneType' is not iterable

这是它在line 173中引用的代码

def main():
    display_instruction()
    computer,human = pieces()
    turn = X
    board = new_board()
    display_board(board)

   while not winner(board):
       if turn == human:
           move = human_move(board, human)
           board[move] == human
       else:
           move = computer_move(board,computer,human)
           board[move] == computer
       display_board(board)
       congrats_winner(the_winner,computer, human)

错误发生在以下函数中:

def human_move(board,human):
'''Get human move'''
legal = legal_moves(board)
move = None
while move not in legal:
    move = ask_number('Where will you move? (0-8): ',0, NUM_SQUARES)
    if move not in legal:
        print ('\nThat square is already occupied, foolish human. Choose another.\n')
print('Fine...')
return move

我尝试将 move = None 更改为 move = ' ' 但这没有任何区别。有任何想法吗?

根据要求,这里是legal_moves的函数

def legal_moves(board):
'''Creates a legal list of moves'''
   moves = []
   for square in range(NUM_SQUARES):
      if board[square] == EMPTY:
          moves.append(square)

【问题讨论】:

  • 什么是legal?那是不可迭代的,不是move。显然,legal 是 None 但它应该是什么?
  • legal_moves 返回什么?
  • 如果您需要额外帮助,请发布legal_moves的定义

标签: python python-3.x


【解决方案1】:

需要返回moves列表:

def legal_moves(board):
    '''Creates a legal list of moves'''
    moves = []
    for square in range(NUM_SQUARES):
        if board[square] == EMPTY:
            moves.append(square)
    return moves

【讨论】:

    【解决方案2】:

    您忘记在 legal_moves 中返回任何内容

    一个优雅的解决方案是使用'yield square'而不是移动列表

    【讨论】:

    • 我不确定yield square 是什么,但希望我能学会。这个答案很有帮助,但亨利的似乎更合适
    • for 循环需要一个可迭代的。生成器是一种简单有效的制造方法。
    • 生成器即时创建返回值,而不是将它们存储在列表中(如您的“移动”),您可以查看stackoverflow.com/a/1756156/1562285wiki.python.org/moin/Generators
    【解决方案3】:

    你的问题是你不能在 none 变量上做一个 while 循环你试图不计算任何东西所以这就是问题......

    如果您提供代码对您有帮助

    【讨论】:

    • 小提琴是什么意思?喜欢在我的整个代码中弹出?
    • 这是误导性的 - 您不能对 None 进行成员资格测试(即使用 in)。 while None 是有效的 Python
    • 你建议它改写成什么?
    猜你喜欢
    • 2011-10-04
    • 1970-01-01
    • 2019-04-15
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多