python change variable outside function code example

Example 1: 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 2: 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

Example 3: accessing a variable from outside the function in python

# for accessing a variable from outside the function then create that variable
# as an attribute of the function
def hi():
    # other code...
    hi.bye = 42  # Create function attribute.
    sigh = 10

hi()
print(hi.bye)  # -> 42