Rishabh
Rishabh

Reputation: 78

global variable error in Python

I am learning Python on my own and I am baffled on what is wrong in the following code

glob_var = 0

def print_glob_var():

    s = 0

    while glob_var > 0:
        s = s+1
        glob_var = glob_var - 1
    return s
    #print (globvar)     

def main():

    global glob_var    
    glob_var = 4
    print_glob_var()

main()

I am getting error "UnboundLocalError: local variable 'glob_var' referenced before assignment" . However when I use only the print the code block works fine.

What I am doing wrong. I am using Python 3.5.2

Upvotes: 0

Views: 566

Answers (3)

ubundows
ubundows

Reputation: 431

glob_var = 4

def print_glob_var():
    global glob_var        # Set glob_var as global
    s = 0

    while glob_var > 0:
        s = s+1            # You can do s += 1 here
        glob_var = glob_var - 1
        print(glob_var)    # Your commented out print() was after the return statement
    return s               # so it would never be reached.

def main():
    print_glob_var()

main()

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36013

Python analyses the body of print_glob_var, sees an assignment to glob_var (specifically glob_var = glob_var - 1) and no global statement, and decides based on that that glob_var is a local variable that it expects to see defined within the function. If you remove the assignment you will no longer get this error, although of course that creates new problems. Alternatively you could add global glob_var to the function. Including it in main is not enough, you need that statement everywhere the variable is used.

This is the kind of reason that using non-constant global variables in Python is a bad idea. Learn about classes.

Upvotes: 1

barak manos
barak manos

Reputation: 30136

In order to change the value of a global variable inside a function, you must declare it global inside the function. You seem to do so in function main, but not in function print_glob_var.

Upvotes: 1

Related Questions