Python - Introduction Variable scope

Introduction

Variables may be assigned in three different places, corresponding to three different scopes:

Where assigned Scope
a variable is assigned inside a def local to that function.
a variable is assigned in an enclosing def nonlocal to nested functions.
a variable is assigned outside all defs global to the entire file.

Variable scopes are determined entirely by the locations of the variables in the source code.

In the following module file, the X = 99 assignment creates a global variable named X.

This X is visible everywhere in this file.

The X = 88 assignment creates a local variable X which visible only within the def statement:

X = 99     # Global (module) scope X 
def func(): 
    X = 88 # Local (function) scope X: a different variable 

Even though both variables are named X, their scopes make them different.

Demo

X = 88                         # Global X 
def func(): 
   X = 99                     # Local X: hides global, but we want this here 
func() #  ww w.j a  v  a  2s . com
print(X)                       # Prints 88: unchanged

Result

Related Topics

Quiz