简体   繁体   中英

How to increment global variable from function in python

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

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.

If you want to modify variable outside of the scope of the function you need to use the global keyword

my_var = True # Declare a variable on the global scope
def my_function():
     global my_var # tell the interpreter that you want to use the global "my_var"
     my_var = False # Change global my_var value

my_function() # call the function
print my_var # check result

Be advised however that it is not considered a good practice to do so.

You should try to isolate as much as you can the scopes in your code to make it more readable.

my_var = 3 # Declare a variable on the global scope
def my_function(my_var):
     return my_var + 1

my_var = my_function(my_var) # call the function and assign result to global variable
print my_var # check result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM