Retaining variables within functions - Raspberry Pi Forums
my apologies if question has been answered elsewhere, searching forum doesn't seem come anything.
newbie python, wondering if it's possible retain variable values within functions, rather getting 'unboundlocalerror: local variable 'x' referenced before assignment' error.
seems once function has completed, of variable values used within function 'discarded' (not remembered when function called again).
here's (rather simplified) example;this works fine when 'any_function' called first time (obviously), errors subsequent calls. within function, want 'x' 0 if second parameter pass (count) '1'. otherwise, want 'x' keep increasing. there simple way of implimenting this?
gratefully welcome.
newbie python, wondering if it's possible retain variable values within functions, rather getting 'unboundlocalerror: local variable 'x' referenced before assignment' error.
seems once function has completed, of variable values used within function 'discarded' (not remembered when function called again).
here's (rather simplified) example;
code: select all
# function want retain value of 'x' within function def any_function(value,count): if count == 1: x = 0 x = x + 1 z = value [x] # 'z' here... return() # # main program... y = 0 number = [1, 20, 6, 55, 42, 100] # w in range (6): # here... y = y + 1 any_function(number,y) # carry on doing else here...
gratefully welcome.
put "x = 0" on top of script (making global variable of module)
start function with
global x
changes x written global variable x
start function with
global x
changes x written global variable x
raspberrypi
Comments
Post a Comment