Geek Slack

Introduction to Python
About Lesson



Python Scope


Python Scope

Scope refers to the region of a program where a variable is accessible. Python follows a hierarchical structure for scoping, known as the LEGB rule:

  • Local: Inside the current function.
  • Enclosing: Inside enclosing functions (for nested functions).
  • Global: At the top level of the module (or script).
  • Built-in: In the built-in namespace.

1. Local Scope

Variables declared within a function have local scope and are accessible only within that function.

Example:

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

my_func()  # Output: 10
# print(x)  # Raises NameError: name 'x' is not defined

2. Enclosing Scope

Variables in enclosing functions are accessible in nested functions.

Example:

def outer_func():
    y = 20
    def inner_func():
        print(y)
    inner_func()

outer_func()  # Output: 20

3. Global Scope

Variables declared at the top level of a module are in the global scope and can be accessed from any part of the module.

Example:

x = 30

def my_func():
    print(x)

my_func()  # Output: 30

4. Built-in Scope

Python has several built-in functions and constants that are accessible from anywhere in the code.

Example:

print(abs(-5))  # Output: 5
print(len([1, 2, 3]))  # Output: 3

Conclusion

Understanding scope is crucial for writing Python code that behaves as expected. By knowing where variables are accessible, you can avoid naming conflicts and write cleaner and more maintainable code.

Join the conversation