As a newbie to Python, I was wondering if it's possible to retain variable values within functions, rather than getting the 'UnboundLocalError: local variable 'x' referenced before assignment' error.
It seems that once a function has completed, all of the variable values used within that function are simply 'discarded' (not remembered when the function is called again).
Here's my (rather simplified) example;
Code: Select all
# the function where I want to retain the value of 'x' within the function def any_function(value,count): if count == 1: x = 0 x = x + 1 z = value [x] # do something with 'z' here... return() # # Main program... y = 0 number = [1, 20, 6, 55, 42, 100] # for w in range (6): # do something here... y = y + 1 any_function(number,y) # carry on doing something else here...
Any help will be gratefully welcome.