Python - Introduction global Statement


The global statement tells Python that a function plans to change one or more global names.

Global names are variables assigned at the top level of the enclosing module file.

Global names may be referenced within a function without being declared.


X = 88                         # Global X 
def func(): 
    global X # from  ww  w  .jav a2s.c om
    X = 99                     # Global X: outside def 
print(X)                       # Prints 99


Here, we've added a global declaration to the example here, such that the X inside the def now refers to the X outside the def.

Consider the following code


y, z = 1, 2                    # Global variables in module 
def all_global(): 
    global x                   # Declare globals assigned 
    x = y + z                  # No need to declare y, z: LEGB rule
# from  w w  w  .  ja v a 2  s.c  om

Here, x, y, and z are all globals inside the function all_global.

y and z are global because they aren't assigned in the function.

x is global because it was listed in a global statement to map it to the module's scope explicitly.

Without the global here, x would be considered local by virtue of the assignment.

Related Topic