python global scope 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: how to make variable global in python

global variable
variable = 'whatever'

Example 3: how does scope work in python

a = 5
b = 3

def f1():
  a = 2
  print(a)
  print(b)
  
print(a)   # Will print 5
f1()       # Will print 2 and 3

Example 4: how to declare global variable in python

global n
n = 'whatever'