How to increment global variable from function in python
Question: I'm stuck by a simple increment function like

    
    
    from numpy import *
    from pylab import *
    
    ## setup parameters and state variables
    T       = 1000                # total time to simulate (msec)
    dt      = 1                   # simulation time step (msec)
    time    = arange(0, T+dt, dt) # time array
    Vr      = -70                 #reset
    El      = -70                
    
    ## LIF properties
    Vm      = zeros(len(time))      # potential (V) trace over time 
    Rm      = 10                    # resistance (mOhm)
    tau_m   = 10                    # time constant (msec)
    Vth     = -40                   # spike threshold (V)
    
    ## Input stimulus
    I       = 3.1                 # input current (nA)
    Vm[0] = -70
    
    Fr = 0
    
    ## iterate over each time step
    def func(Ie, Vm, Fr):
        for i, t in enumerate(time):
            if i == 0:
                Vm[i] = -70
            else: 
                Vm[i] = Vm[i-1] + (El- Vm[i-1] + Ie*Rm) / tau_m * dt
                if Vm[i] >= Vth:
                    Fr += 1
                    Vm[i] = El
         return
    
    Ie = 3.1
    func( Ie, Vm, Fr)
    print Fr
    
    ## plot membrane potential trace  
    plot(time, Vm)
    title('Leaky Integrate-and-Fire')
    ylabel('Membrane Potential (mV)')
    xlabel('Time (msec)')
    ylim([-70,20])
    show()
    

Why after the func is called, the Fr is still 0?

I know it's simple but I have wasted long time on this

Thank you


Answer: You have two Fr variables in different scopes

    
    
    Fr = 0
    

Is outside of your function, thus never changed.

    
    
    Fr += 1
    

Is inside a function and will be incremented, but this is a different
variable.

Here is the solution (one of the possible ones):

    
    
    def func(Ie, Vm, Fr):
        for i, t in enumerate(time):
            if i == 0:
                Vm[i] = -70
            else: 
                Vm[i] = Vm[i-1] + (El- Vm[i-1] + Ie*Rm) / tau_m * dt
                if Vm[i] >= Vth:
                    Fr += 1
                    Vm[i] = El
         return Fr
    

Then, just do

    
    
    Fr = func(Ie, Vm, Fr)
    

One more tip. If your `Fr` variable is always 0 by default you can do this:

    
    
    def func(Ie, Vm, Fr=0):
    

when defining the function, and pass the third paramenter only when you need
something different that 0.

