Python Tutorial - Variable Scope

Python Exercise Lists

The so-called scope is the effective range of the variable, which is the scope within which the variable can be used. Some variables can be used anywhere in the entire code, some variables can only be used inside functions, and some variables can only be used inside for loops.

The scope of a variable is determined by the location where the variable is defined. For variables defined in different locations, its scope is different. In this section we only cover two types of variables, local variables and global variables.

Python Local Variables

The scope of a variable defined inside a function is also limited to the inside of the function. It cannot be used if outside of function. We call such a variable a local variable.

You know, when the function is executed, Python will allocate a temporary storage space for it, and all variables defined inside the function will be stored in this space. After the function is executed, this temporary storage space will be released and recycled, and the variables stored in this space will no longer be used.

For example:

def demo():
    website = "http://www.freelearningpoints.com/python/"
    print ("internal function add =", website)

demo()
print ("outside function add =", website)
           

The output is:

internal function add = http://www.freelearningpoints.com/python/
---------------------------------------------------------------------------
NameError      Traceback (most recent call last)
[ipython-input-20-f273d666f43f] in [module]
4
5 demo()
----> 6 print ("outside function add =", website)
NameError: name 'website' is not defined

It can be seen that if you try to access its internally defined variables outside the function, the Python interpreter will report a NameError and prompt us that we have not defined the variable to be accessed. This also confirms that when the function is called, the internally defined variables will be destroyed and recycled.

It is worth mentioning that the parameters of the function are also local variables and can only be used inside the function. Example:

def demo (name, website):
    print ("function internal name =", name)
    print ("internal function add =", website)
demo ("Python Tutorial", "http://www.freelearningpoints.com/python/")
print ("function external name =", name)
print ("outside function add =", website)
           

The output is:

function internal name = Python Tutorial
internal function add = http://www.freelearningpoints.com/python/
---------------------------------------------------------------------------
NameError      Traceback (most recent call last)
[ipython-input-21-1a92feaee38d] in [module]
3 print ("internal function add =", website)
4 demo ("Python Tutorial", "http://www.freelearningpoints.com/python/")
----> 5 print ("function external name =", name)
6 print ("outside function add =", website)
NameError: name 'name' is not defined

Because the Python interpreter runs the program code line by line, it only prompts me that "name is not defined". In fact, accessing the website variable outside the function will also report the same error.

Python Global Variables

In addition to defining variables inside functions, Python also allows variables to be defined outside of all functions. Such variables are called global variables.

Unlike local variables, the default scope of global variables is the entire program, that is, global variables can be used both outside and inside functions.

There are two ways to define global variables:

The variables defined outside the function must be global variables, for example:

website = "http://www.freelearningpoints.com/tutorials/"
def text ():
    print ("Function body access:", website)
text ()
print ('External function access:', website)
           

The output is:

Function body access: http://www.freelearningpoints.com/tutorials/
External function access: http://www.freelearningpoints.com/tutorials/

Define global variables in the function body. Even if a variable is decorated with the global keyword, the variable becomes a global variable. Example:

def text():
    global website
    website= "http://www.freelearningpoints.com/exerises/"
    print ("Function body access:", website)
text ()
print ('External function access:', website)
           

The output is:

Function body access: http://www.freelearningpoints.com/exerises/
External function access: http://www.freelearningpoints.com/exerises/

Note that when using the global keyword to modify a variable name, you cannot directly assign an initial value to the variable, otherwise a syntax error will be thrown.

Get Python Variables in the Specified Scope

In some specific scenarios, we may need to get all the variables in a scope (globally or locally). Python provides the following three methods:

1) Global Function

The global function is a built-in function of Python. It can return a dictionary containing all variables in the global scope. Each key-value pair in the dictionary, the key is the variable name, and the value is the value of the variable.

For example:

#Global variables
Py_name = "Python Tutorial"
Py_website = "http://www.freelearningpoints.com/python/"
def text ():
    #Local variables
    Ny_name = "Numpy tutorial"
    Ny_website = "http://www.freelearningpoints.com/numpy/"
print (globals ())
           

The output is:

{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': [module 'builtins' (built-in)], '__builtins__': [module 'builtins' (built-in)], '_ih': ['', 'def dis_str (str1, str2):\n

Note that the dictionary returned by the global function contains many variables by default. These are all built into the main Python program. The reader doesn't need to worry about them for now.

As you can see, by calling the global function, we can get a dictionary containing all global variables. And, with this dictionary, we can also access the specified variable and even modify its value if needed. For example, based on the above program, add the following statement:

print (globals ()['Py_name'])
globals () ['Py_name'] = "Getting Started with Python"
print (Py_name)
           

The output is:

Python Tutorial
Getting Started with Python

2) Local Function

The local function is also one of Python's built-in functions. By calling this function, we can get a dictionary containing all variables in the current scope. The so-called "current scope" here means that calling the local function inside the function will get a dictionary containing all local variables; and calling the local function in the global template has the same function as the global function.

For example:

#Global variables
Py_name = "Python Tutorial"
Py_website = "http://www.freelearningpoints.com/python/"
def text ():
    #Local variables
    Ny_name = "Numpy tutorial"
    Ny_website = "http://www.freelearningpoints.com/numpy/"
    print ("locals: inside the function")
    print (locals ())
text ()
print ("locals: outside the function")
print (locals ())
           

The output is:

locals: inside the function
{'Ny_name': 'Numpy tutorial', 'Ny_website': 'http://www.freelearningpoints.com/numpy/'}
locals: outside the function
{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment'}

When using the local function to get all global variables, like the global function, the dictionary returned by the default contains a lot of variables, these are built into the Python main program, the reader does not care about them for the time being.

Note that when using the locals () function to obtain a dictionary of all local variables, you can access the corresponding variable value through the specified key like the globals() function, but you cannot modify the variable value. Example:

#Global variables
Py_name = "Python Tutorial"
Py_website = "http://www.freelearningpoints.com/python/"
def text ():
    #Local variables
    Ny_name = "Numpy tutorial"
    Ny_website = "http://www.freelearningpoints.com/numpy/"
    print (locals () ['Ny_name'])
    locals () ['Ny_name'] = "Numpy tutorial"
    print (Ny_name)
text ()
           

The output is:

Numpy tutorial
Numpy tutorial

Obviously, a dictionary of local variables returned by locals() can be used to access the variables, but the value of the variables cannot be modified.

3) Vars (object)

The vars function is also a Python built-in function. Its function is to return a dictionary of all variables in the specified object range. If you do not pass in an object parameter, vars and locals have exactly the same effect.

Since the reader has not yet learned Python classes and objects, beginners can skip the learning of the function first, wait for the Python class and object, and then return to the function.

For example:

 #Global variables
Py_name = "Python Tutorial"
Py_website = "http://www.freelearningpoints.com/python/"
class Demo:
    name = "Python Tutorial"
    website = "http://www.freelearningpoints.com/python/"
print ("has object:")
print (vars (Demo))
print ("No object:")
print (vars ())
           

The output is:

has object:
{'__module__': '__main__', 'name': 'Python Tutorial', 'website': 'http://www.freelearningpoints.com/python/', '__dict__': [attribute '__dict__' of 'Demo' objects], '__weakref__': [attribute '__weakref__' of 'Demo' objects], '__doc__': None}
No object:
{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None}

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises