Scope of Variable in Python
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:
Transform Your Career
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
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:
Scaler Placement Report and Statistics
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.
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.