What Is Scope Resolution In Python?

What Is Scope Resolution In Python?

Published on October 09 2023

In this tutorial, we will learn about scope resolution in Python. And will also understand what is a local and global scope in detail with an example. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • Scope Resolution
    • Scope refers to the availability and accessibility of an object in the code Or you can say accessibility and the lifetime of a variable.

Types

  • Local
    • The variables declared inside a loop, and the function body are called local variables. And accessible only within that function or loop.
    • This variable is present in the local space and not in the global space.
    • Example
def print_message():
    name = 'TheProgrammingPortal'
    print('Inside Local Scope:' + str(name))
 
print_message()
  • Global
    • Variables declared outside a function or in global space are called global variables
    • These variables can be accessed by any function in the program that is, both inside and outside of each function.
    • Example
name = 'TheProgrammingPortal'
def print_message():
    print('Reading From Global Scope:' + str(name))
print_message()

To know about it, please refer to the official documentation website - official website.