public variable python code example

Example 1: python static variable in function

#You can make static variables inside a function in many ways.
#____________________________________________________________#
"""1/You can add attributes to a function, and use it as a
static variable."""
def foo():
    foo.counter += 1
    print ("Counter is %d" % foo.counter)
foo.counter = 0 

#____________________________________________________________#
"""2/If you want the counter initialization code at the top
instead of the bottom, you can create a decorator:"""
def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            setattr(func, k, kwargs[k])
        return func
    return decorate
  
#Then use the code like this:
@static_vars(counter=0)
def foo():
    foo.counter += 1
    print ("Counter is %d" % foo.counter)

#____________________________________________________________#
"""3/Alternatively, if you don't want to setup the variable
outside the function, you can use hasattr() to avoid an
AttributeError exception:"""
def myfunc():
    if not hasattr(myfunc, "counter"):
        myfunc.counter = 0  # it doesn't exist yet, so initialize it
    myfunc.counter += 1
  
#____________________________________________________________#

Example 2: global variable not working python

trying to assign a global variable in a function will result in the function creating a new variable
with that name even if theres a global one. ensure to declare a as global in the function before any
assignment.

a = 7
def setA(value):
    global a   # declare a to be a global
    a = value  # this sets the global value of a

Example 3: python global variables

global var1
var1 = 'whatever'

Example 4: python access global variable

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

Example 5: global variable python

a = 0

def testFor():
  global a 
  if(a == 0):
    	#run code

Example 6: python local variables

'''Local variables are those that are defined in a block '''
a = 1 #This is NOT a local variable, this is a global variable
def add():
  b = 1 #This IS a local variable
  print(b)
add()
#If we tried to print(b) outside of the add() function, we would get an error