2

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?

2
  • global col should be inside interpret. Commented Oct 8, 2021 at 15:46
  • 1
    Every variable on the left side of an assignment (also augmented ones) in a function is seen as local if not explicitly declared global with "global". Commented Oct 8, 2021 at 15:46

1 Answer 1

5

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, I'll try this. You said I shouldn't use globals. Is there an alternative?
Yes, you should pass variables into functions for them to operate on. I will update my answer with an example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.