Scope of Variable in Python

Video Tutorial
FREE
Scope of a Variable thumbnail
This video belongs to
Python Course for Beginners With Certification: Mastering the Essentials
16 modules
Certificate

In Python, variables act as containers for storing data values. Unlike statically-typed languages such as C/C++/Java, Python doesn't require explicit declaration or typing of variables before use; they are created upon assignment. The variable scope in Python refers to where it can be found and accessed within a program.

Python Local Variables

Local variables in Python are initialized within a function and are unique to that function's scope. They cannot be accessed outside of the function. Let's explore how to define and utilize local variables.

Example

Output:

Function Inside Function

As demonstrated in the example above, the variable x is confined within the function's scope and is inaccessible outside of it. However, it remains accessible to any nested functions within its enclosing function.

Example

Output:

Python Global Variables

In Python, variables defined outside of any function or class, in the main body of the code, are considered global variables. They belong to the global scope and are accessible from within any scope, including both global and local scopes.

Example

Output:

Naming Variables

When operating with the same variable name inside and outside of a function, Python treats them as distinct variables. One exists in the global scope (outside the function), while the other resides in the local scope (inside the function).

Example

Output:

Python Nonlocal Variables

In Python, the nonlocal keyword, like global, declares a variable. However, nonlocal specifically references a variable in an outer enclosing function within a nested function.

Output:

Conclusion

  • Variables are containers for data values, and their scope in python determines where they can be accessed within a program.
  • Local variables are defined within a function and are accessible only within that function's scope.
  • Variables declared outside of functions or classes are termed global variables.
  • The nonlocal keyword allows modifying variables from the outer enclosing function within a nested function.

Learn More