首页 > 解决方案 > “UnboundLocalError:分配前引用的局部变量”使用全局变量后

问题描述

我正在尝试访问我已经尝试过使其成为全局的函数中的变量,但这不起作用。这是我的代码(精简后没有不必要的变量声明):

global col
col = 0
def interpret(text):
  for char in text:
      col += 1

我得到的错误说:

Traceback (most recent call last):
  File "main.py", line 156, in <module>
    interpret(line) (Where I call the function in the rest of the code)
  File "main.py", line 21 (5), in interpret
    col += 1
UnboundLocalError: local variable 'col' referenced before assignment

我怎样才能解决这个问题?

标签: python

解决方案


您需要global在函数中包含以下语句:

col = 0

def interpret(text):
    global col
    for char in text:
        col += 1

在函数外部赋值col会创建变量,但为了能够在函数内部写入,global语句需要在每个函数内部。

顺便说一句,作为一名程序员,您应该非常非常非常努力地不使用全局变量。

您应该将变量传递给函数以供它们操作:

col = 0

def interpret(text, cnt):
    for char in text:
        cnt += 1
    return cnt

text = ...
col = interpret(text, col)  # pass col in and assign it upon return.

推荐阅读