Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a local variable referenced before assignment error? [duplicate]

Tags:

python

The answer should be 2 because first the main() function is called, then the first() function is called, overriding the global variable num = 0 which was defined outside of any functions, therefore rendering it a variable with global scope. Yet I get the following error:

UnboundLocalError: local variable 'num' referenced before assignment  

Why am I getting this error?

def first():
    num = num + 1

def main():
    num = 1
    first()
    print(num)

num = 0

num_result = main()

print(num_result) 
like image 991
Dr.Doom2020 Avatar asked Mar 25 '26 17:03

Dr.Doom2020


1 Answers

The OP wrote (emphasis mine):

The answer should be 2 because first the main() function is called, then the first() function is called, overriding the global variable.

It is not overriding the global variable. Unless you explicitly specify a variable as global, if there is any assignment to the variable in a function, it is assumed to be local. See also the python tutorial on defining functions where it states (emphasis mine):

More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

and the documentation of the global statement (if anyone using Python 3 is looking at this, please also take a look at the (compared to global) very useful nonlocal statement and its PEP 3104).

To "fix" your code:

def first():
    global num
    num = num + 1

def main():
    global num
    num = 1
    first()
    print(num)

num = 0

num_result = main()

print(num_result) 

Do not use global variables in this way please. @LutzHorn has shown in his answer how to do it right.

The reason to avoid global variables is that their effect is hard to test for, and as soon as code gets complex enough, hard to reason about. If every function modifies global variables instead of properly taking parameters and returning values, understanding what the code actually does is hard as soon as one has more than a week or so of distance from it.

like image 137
Jonas Schäfer Avatar answered Mar 28 '26 06:03

Jonas Schäfer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!