首页 > 解决方案 > 当在其中使用全局变量时,函数变得不可迭代

问题描述

这里的初学者,我对解决问题很感兴趣,但也学习它的“如何”和“为什么”

所以我有这个功能:

import random

move = 0

def computer_move():
    global move
    if move == 0:
        while True:
            rand = random.randrange(0, 9)
            if positions[rand].state:
                move = 1
                positions[rand].state = False
                positions[rand].played = 'circle'
                return positions[rand].x,positions[rand].y

在我在函数外部声明“move”变量之前,一切正常,除非每当调用函数时变量重置为 0,所以我必须在外部声明它,自然我必须将它与global. 除了现在当我像这样调用函数时:

x, y = computer_move()

TypeError: cannot unpack non-iterable NoneType object上线了函数调用

我厌倦了一些想法,但似乎没有任何效果。感谢任何帮助或澄清

标签: pythonpython-3.xfunctionglobal-variables

解决方案


None在 Python 中,如果没有return执行,则函数返回。如果 .你的函数可能会None像这样返回move != 0。在这种情况下,x, y = computer_move()将等价于x, y = None,这会导致TypeError.


推荐阅读