VOOZH about

URL: https://www.analyticsvidhya.com/blog/2024/01/understanding-scope-in-python/

⇱ A-Z of Scope in Python - Analytics Vidhya


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Understanding Scope in Python

NISHANT TIWARI Last Updated : 23 Jan, 2024
5 min read

Introduction

Python offers a wide range of features and functionalities. Its clean and readable syntax, extensive standard library, and vibrant community of developers contribute to Python’s popularity and widespread adoption in diverse industries. One of the fundamental concepts in Python is scope, which determines the accessibility and visibility of variables within a program. Understanding scope is crucial for writing efficient and bug-free code. In this comprehensive guide, we will explore the different aspects of scope in Python and how it affects the behavior of variables.

What is Scope in Python?

Scope refers to the region or context in which a variable is defined and can be accessed. It defines the visibility and lifetime of a variable. In Python, there are three types of scope: global scope, local scope, and nonlocal scope.

You can explore Python here: Python

Importance of Understanding Scope in Python

Understanding scope is essential for writing clean and maintainable code. It helps prevent naming conflicts, improves code readability, and enhances reusability. By understanding the different types of scope in Python, developers can write more efficient and bug-free programs.

Global Scope

The global scope refers to a program’s outermost scope. Variables defined in the global scope are accessible from anywhere within the program and have a global lifetime, meaning they exist as long as the program is running.

Local Scope

Local scope refers to the innermost scope of a program, such as a function or a block of code. Variables defined in the local scope are only accessible within that specific scope. These variables have a local lifetime, meaning they are created when the scope is entered and destroyed when the scope is exited.

Nonlocal Scope

Nonlocal scope is a scope that is neither global nor local. It is used when we want to modify a variable in an outer (but non-global) scope from an inner scope. Nonlocal variables are accessible within nested functions or inner scopes.

Global, Local, and Nonlocal Variables in Python

Global Variables

The Global variables are defined outside any function or block of code. They are accessible from anywhere within the program. To access a global variable within a function, we need to use the `global` keyword.

Code

x = 10
def my_function():
    global x
    print(x)
my_function()

Output

10

Local Variables

Local variables are defined within a function or block of code. They are only accessible within that specific scope. Local variables can have the same name as global variables, but they are entirely separate entities.

Code

x = 10
def my_function():
    x = 20
    print(x)
my_function()
print(x)

Output

20

10

Nonlocal Variables

Nonlocal variables are used to modify variables in an outer (but non-global) scope from an inner scope. They are accessible within nested functions or inner scopes.

Code

def outer_function():
    x = 10
    def inner_function():
        nonlocal x
        x = 20
    inner_function()
    print(x)
outer_function()

Output

20

Also read: Introduction to Python Programming (Beginner’s Guide)

Scoping Rules in Python

LEGB Rule

Python follows the LEGB rule to determine the scope of a variable. LEGB stands for Local, Enclosing, Global, and Built-in. When a variable is referenced, Python searches for it in the following order: local scope, enclosing scope, global scope, and built-in scope.

Code

x = 10
def my_function():
    x = 20
    def inner_function():
        x = 30
        print(x)
    inner_function()
    print(x)
my_function()

Output

30

20

Enclosing Scope

Enclosing scope refers to the scope of the outer function when there are nested functions. Inner functions can access variables from the enclosing scope.

Code

def outer_function():
    x = 10
    def inner_function():
        print(x)
    inner_function()
outer_function()

Output

10

Nested Scopes

Nested scopes occur when there are multiple levels of nested functions. Each nested function has its own scope, and they can access variables from outer scopes.

Code

def outer_function():
    x = 10
    def inner_function():
        y = 20
        def nested_function():
            print(x + y)
        nested_function()
    inner_function()
outer_function()

Output

30

Scope and Functions in Python

Function Scope

In Python, functions create their own local scope. Variables defined within a function are only accessible within that function.

Code

def my_function():
    x = 10
    print(x)
my_function()
print(x)

Output

10

Error: NameError: name β€˜x’ is not defined

Function Arguments and Scope

Function arguments are also local variables within the function’s scope. They are created when the function is called and destroyed when the function completes its execution.

Code

def my_function(x):
    print(x)
my_function(10)
print(x)

Output

10

Error: NameError: name β€˜x’ is not defined

Returning Values from Functions

Functions can return values that can be assigned to variables in the calling scope. The returned values are accessible outside the function.

Code

def add_numbers(a, b):
    return a + b
result = add_numbers(10, 20)
print(result)

Output

30

Scope and Loops in Python

Loop Scope

In Python, variables defined within a loop have a local scope and are only accessible within that loop.

Code

for i in range(5):
    x = i * 2
    print(x)
print(x)

Output

8

Scope Inside Loops Compared to C/C++

Unlike C/C++, Python does not create a new scope for each iteration of a loop. Variables defined within a loop are accessible outside the loop.

Code

for i in range(5):
    x = i * 2
print(x)

Output

8

Scope and Modules in Python

Module Scope

Module scope refers to the scope of variables defined within a module. These variables are accessible from any part of the module.

Code

# module.py
x = 10
def my_function():
    print(x)
# main.py
import module
print(module.x)
module.my_function()

Output

10

10

Importing and Using Variables from Other Modules

Variables defined in one module can be imported and used in another module using the `import` statement.

Code

# module1.py
x = 10
# module2.py
import module1
print(module1.x)

Output

10

Scope and Classes in Python

Class Scope

Class scope refers to the scope of variables defined within a class. These variables are accessible within the class and its instances.

Code

class MyClass:
    x = 10
    def my_method(self):
        print(self.x)
my_object = MyClass()
print(my_object.x)
my_object.my_method()

Output:

10

Instance Variables and Class Variables

Instance variables are defined within methods of a class and are unique to each instance of the class. Class variables are defined outside any method and are shared among all instances of the class.

Code

class MyClass:
    class_variable = 10
    def __init__(self, instance_variable):
        self.instance_variable = instance_variable
object1 = MyClass(20)
object2 = MyClass(30)
print(object1.class_variable)
print(object2.class_variable)
print(object1.instance_variable)
print(object2.instance_variable)

Output

10

10

20

30

Scope and Exception Handling in Python

Scope of Exception Variables

Exception variables are local variables within the scope of an exception handler. They are created when an exception is raised and destroyed when the exception is handled.

Code

try:
    x = 10 / 0
except ZeroDivisionError as e:
    print(e)
print('a')
print(e)

Output

division by zero

a

Error: NameError: name β€˜e’ is not defined

Handling Exceptions in Different Scopes

Exceptions can be handled at different levels of scope, such as within a function or at the global level. The scope in which an exception is handled affects the visibility of exception variables.

Code

def my_function():
    try:
        x = 10 / 0
    except ZeroDivisionError as e:
        print(e)
my_function()
print(e)

Output

division by zero

Error: NameError: name β€˜e’ is not defined

Conclusion

Understanding scope is crucial for writing efficient and bug-free Python code. Developers can write clean and maintainable code by grasping the concepts of global scope, local scope, and nonlocal scope. Scoping rules, function scope, loop scope, module scope, class scope, and exception handling all play a significant role in determining the visibility and accessibility of variables within a program. By following the guidelines outlined in this comprehensive guide, developers can leverage the power of scope in Python to write robust and reliable applications.

Elevate your skills, advance your career, and stay ahead in the dynamic world of technology with the Certified AI & ML BlackBelt PlusProgram. Limited spots are available. Enroll now to secure your place and embark on a transformative journey into the future of artificial intelligence and machine learning. Don’t miss out on this exclusive opportunity! Click here to join the elite ranks of Certified AI & ML BlackBelts!

Seasoned AI enthusiast with a deep passion for the ever-evolving world of artificial intelligence. With a sharp eye for detail and a knack for translating complex concepts into accessible language, we are at the forefront of AI updates for you. Having covered AI breakthroughs, new LLM model launches, and expert opinions, we deliver insightful and engaging content that keeps readers informed and intrigued. With a finger on the pulse of AI research and innovation, we bring a fresh perspective to the dynamic field, allowing readers to stay up-to-date on the latest developments.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner