Python Crash Course | Python Global variables, Local variables, and Nonlocal variables: A Comprehensive Guide

Python Crash Course | Python Global variables, Local variables, and Nonlocal variables: A Comprehensive Guide

 

In Python, variables play a vital role in storing and managing data throughout the program. Variables are classified into three primary categories: global variables, local variables, and nonlocal variables. This article provides a comprehensive guide to understanding these variables, their scopes, and how they interact within the Python environment. We will also provide coding examples and figures to further illustrate their usage and behavior.

Global variables

Global variables are variables defined outside any function or class. They are accessible from any part of the code, including inside functions and classes. This makes them useful for storing data that needs to be accessed from multiple parts of the code.

Defining global variables

To define a global variable, simply declare it outside any function or class. For example:

global_var = "I am a global variable"

def print_global_var():
    print(global_var)

print_global_var()  # Output: I am a global variable

In this example, global_var is a global variable, as it is defined outside the function print_global_var. The function can access and print the global variable.

Modifying global variables

To modify a global variable from within a function, you must use the global keyword before the variable name. This tells Python that you are referring to the global variable instead of creating a new local one.

global_var = 10

def modify_global_var():
    global global_var
    global_var += 5

print(global_var)  # Output: 10

modify_global_var()

print(global_var)  # Output: 15

In this example, we use the global keyword inside the modify_global_var function to indicate that we are referring to the global_var global variable. We then increment its value by 5.

Local variables

Local variables are variables defined inside a function or a class. Their scope is limited to the function or class in which they are defined. They cannot be accessed from outside the function or class.

Defining local variables

To define a local variable, declare it inside a function or class. For example:

def print_local_var():
    local_var = "I am a local variable"
    print(local_var)

print_local_var()  # Output: I am a local variable

In this example, local_var is a local variable, as it is defined inside the print_local_var function. It can only be accessed and printed from within that function.

Variable shadowing

When a local variable has the same name as a global variable, the local variable shadows the global one inside the function. This means that the local variable takes precedence over the global variable within that function’s scope.

global_var = "I am a global variable"

def print_var():
    global_var = "I am a local variable"
    print(global_var)

print_var()  # Output: I am a local variable
print(global_var)  # Output: I am a global variable

In this example, the print_var function has a local variable with the same name as the global global_var. Inside the function, the local variable shadows the global one, and the output is “I am a local variable”. Outside the function, the global variable is still accessible and unchanged.

Nonlocal variables

Nonlocal variables are used in nested functions. They allow a nested function to access and modify a variable from the containing function. Nonlocal variables are neither global nor local to the nested function.

Defining nonlocal variables

To define a nonlocal variable, use the nonlocal keyword before the variable name in the nested function. This tells Python that the variable is not a local variable and should be searched for in the nearest enclosing scope (excluding the global scope). For example:

def outer_function():
    outer_var = "I am a nonlocal variable"

    def inner_function():
        nonlocal outer_var
        outer_var += " - modified by inner_function"
        print(outer_var)
    inner_function()

outer_function()
# Output: I am a nonlocal variable - modified by inner_function

In this example, outer_var is defined in the outer_function and modified in the inner_function. By using the nonlocal keyword, we indicate that outer_var should be searched for in the nearest enclosing scope, which is the outer_function.

Nonlocal variables vs. global variables

Nonlocal variables are different from global variables. While global variables are accessible from any part of the code, nonlocal variables are only accessible within the nested function’s containing scope. Here is an example to demonstrate the difference:

global_var = "I am a global variable"

def outer_function():
    nonlocal_var = "I am a nonlocal variable"
    def inner_function():
        global global_var
        nonlocal nonlocal_var
        global_var += " - modified by inner_function"
        nonlocal_var += " - modified by inner_function"
    inner_function()
    print(nonlocal_var)

outer_function()
# Output: I am a nonlocal variable - modified by inner_function

print(global_var)
# Output: I am a global variable - modified by inner_function

In this example, we have a global variable global_var and a nonlocal variable nonlocal_var. The inner_function modifies both variables. The nonlocal variable can only be accessed and printed from within the outer_function, while the global variable can be accessed and printed from outside the outer_function.

Summary

Understanding the different types of variables and their scopes is essential for efficient and effective programming in Python. Global variables can be accessed and modified from any part of the code, making them suitable for storing data that needs to be shared among various parts of the program. Local variables are limited in scope and can only be accessed and modified within the function or class in which they are defined. Nonlocal variables enable nested functions to access and modify variables from their containing functions, allowing for more flexible and modular code structures.

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)


Learn by Coding: Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!