Python-局部变量';x';分配前参考

Python-局部变量';x';分配前参考,python,Python,我是Python的初学者(如果这是一个愚蠢的错误,请容忍我…) 我有一个函数,当if条件不满足时,每次调用它时,它都会递增一个全局变量x 我的函数如下所示: #x is declared here as a global variable x = 0 def gen_pos(tag): if next(tag.iterancestors(),None)==None: x = 0 y = 0 else: #increment her

我是Python的初学者(如果这是一个愚蠢的错误,请容忍我…)

我有一个函数,当if条件不满足时,每次调用它时,它都会递增一个全局变量x

我的函数如下所示:

#x is declared here as a global variable
x = 0

def gen_pos(tag):
    if next(tag.iterancestors(),None)==None:
        x = 0
        y = 0
    else:
        #increment here
        x+= 1
        y = 0
        while tag is not None:
            y -= 1
            tag = tag.getparent()
    return zip(x,y)
但是,我得到了一个错误:

local variable 'x' referenced before assignment
错误的位置在中

x+=1

你知道为什么会这样吗?提前谢谢

您想在函数中使用

global x
您的代码将如下所示

x = 0
def gen_pos(tag):
    global x
    if next(tag.iterancestors(),None)==None:
        x = 0
        y = 0
    else:
        #increment here
        x+= 1
        y = 0
        while tag is not None:
            y -= 1
            tag = tag.getparent()
    return zip(x,y)

您应该声明您使用了一个全局变量

#x is declared here as a global variable
x = 0

def gen_pos(tag):
    global x
   

您可以在

中了解有关此问题的更多信息。函数修改全局变量几乎没有任何用处。这样做很难跟踪哪些函数会影响哪些变量。如果您将
x
作为一个参数传递,它会更清楚地显示哪些因素会影响哪些其他因素

另外,
zip
参数必须是可编辑的。我想你是想返回一个元组

def gen_pos(tag, x):
    if next(tag.iterancestors(),None)==None:
        return 0, 0
    y = 0
    while tag is not None:
        y -= 1
        tag = tag.getparent()
    return x + 1, y

还要注意,如果未将
x
声明为全局变量,则语句
x=0
将创建一个与全局变量不同的局部变量。