global and local variables python code example

Example 1: 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 2: 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 3: how to declare global variable in python

global n
n = 'whatever'

Example 4: global variables python

global x
x=1