global scope python 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: global variable python

a = 0

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

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: python variable scope

a = 5

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

Example 5: python globals

globals 1, 2, 3