Introduction

Global variables are the one that are defined and declared outside a function and we need to use them inside a function. If a variable with same name is defined inside the scope of function as well then it will refer variable given inside the function only and not the global value.

So when you define variables inside a function definition, they are local to this function by default. This means that anything you will do to such a variable in the body of the function will have no effect on other variables outside of the function, even if they have the same name. This means that the function body is the scope of such a variable, i.e. the enclosing context where this name with its values is associated.

A variable can’t be both local and global inside of a function. To tell Python, that we want to use the global variable, we have to explicitly state this by using the keyword “global”, as can be seen in the following example:

def f(): 
    # Using global variable
    global s 
    print s 

# Global scope 
s = "Python"

f()

 

Global Variables in Nested Functions

Global statement inside of the nested function g does not affect the variable x of the function f, i.e. it keeps its value 42 (see below example). We can also deduce from this example that after calling f() a variable x exists in the module namespace and has the value 43. This means that the global keyword in nested functions does not affect the namespace of their enclosing namespace. A variable defined inside of a function is local unless it is explicitly marked as global. In other words, we can refer a variable name in any enclosing scope, but we can only rebind variable names in the local scope by assigning to it or in the module-global scope by using a global declaration.

def f():
  x = 42
  def g():
    global x
    x = 43
  
  print("Before calling g: " + str(x))
  print("Calling g now:")
  
  g()
  
  print("After calling g: " + str(x))
    
f()
print("x in main: " + str(x))

# Program Output:
Before calling g: 42
Calling g now:
After calling g: 42
x in main: 43

 

nonlocal Variables

Python3 introduced nonlocal variables as a new kind of variables. nonlocal variables have a lot in common with global variables. One difference to global variables lies in the fact that it is not possible to change variables from the module scope. This means that nonlocal bindings can only be used inside of nested functions. A nonlocal variable has to be defined in the enclosing function scope. If the variable is not defined in the enclosing function scope, the variable cannot be defined in the nested scope. This is another difference to the “global” semantics.

def f():
  x = 42
  def g():
    nonlocal x
    x = 43

  print("Before calling g: " + str(x))
  print("Calling g now:")

  g()
  print("After calling g: " + str(x))
    
x = 3
f()
print("x in main: " + str(x))

# Program Output:
Before calling g: 42
Calling g now:
After calling g: 4