Donoru
Donoru

Reputation: 155

"UnboundLocalError: local variable referenced before assignment" After using global variables

I'm trying to access a variable inside a function that I've already tried making global, but that doesn't work. Here's my code (trimmed down with no unnecessary variable declarations):

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

The error I get says:

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

How can I fix this?

Upvotes: 2

Views: 2285

Answers (1)

quamrana
quamrana

Reputation: 39354

You need to have the global statement inside the function:

col = 0

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

Assigning col outside the function creates the variable, but to be able to write to it inside a function, the global statement needs to be inside each function.

btw As a programmer you should try very, very, very hard not to use globals.

You should pass variables into functions for them to operate on:

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.

Upvotes: 5

Related Questions