对于一个全局变量,如果在函数内部,没有对该变量进行全局声明,则变量就会被Python解释器认为是局部变量而非全局变量。
因此,在函数内需要再次对该变量进行全局声明:

global  x
x = []

def run():
    global x
    for i in range(10):
        x.append(i)
    # 打印x
    print(x)

# 调用函数
run()    

Python问题:UnboundLocalError: local variable 'xxx' referenced before assignment

相关文章:

  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
猜你喜欢
  • 2022-12-23
  • 2021-08-20
  • 2021-09-27
  • 2021-09-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案