"UnboundLocalError: local variable referenced before assignment" 使用全局变量后



我试图访问一个函数内的变量,我已经尝试全局,但这不起作用。下面是我的代码(删去了不必要的变量声明):

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

我该如何解决这个问题?

您需要在函数中使用global语句:

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

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

作为一个程序员,你应该尝试very,veryvery很难不使用全局变量。

应该将变量传递给函数,以便对其进行操作:

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.

最新更新