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;

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... 
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.

put "x = 0" on top of script (making global variable of module)
start function with
global x

changes x written global variable x


raspberrypi



Comments

Popular posts from this blog

Convierte tu Raspberry en un NAS. Firmware fvdw-sl 15.3 - Raspberry Pi Forums

How to format a Get Request

avrdude: verification error, first mismatch at byte 0x0000 0x0c != 0x62