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
3 Answers 3
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.
Comments
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.
Comments
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()
globalkeyword inside the function body