Python - Introduction global Statement

Introduction

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.

Demo

X = 88                         # Global X 
def func(): 
    global X # from ww w.j a  v a 2 s. co m
    X = 99                     # Global X: outside def 
func() 
print(X)                       # Prints 99

Result

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

Demo

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  www .j  a va2  s. c  o  m

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