
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Variable Scopes in Python Modules
What is Variable Scope in Python?
Variable scope in Python defines where a variable can be assigned or modified in your code. It determines the visibility and lifetime of variables, controlling which parts of your program can use particular variables.
Variable scope in Python provides many benefits, which include -
- To avoid naming conflicts
- To manage memory efficiently
- To write more maintainable and modular code
- To prevent unnecessary variable modifications
Python has four main levels of variable scope, which is the LEGB Rule. This stands for -
- Local Scope(L)
- Global (G)
- Enclosing (E)
- Built-in (B)
Local Scope
The variables that are defined in the function are variables with a local scope. The function body contains a definition for these variables.
Example
Let's use an illustration to help you comprehend this idea. One variable, num, was used in example 1. Num = 0 is not a local variable because it is defined outside of the function. According to our definition, a local variable is declared inside the body of a function. Here, the local variable num=1 is set and printed inside the demo function.
num=0 def demo(): #print(num) num=1 print("The Number is:",num) demo()
The output generated is as follows -
The Number is: 1
Global Range
A global scope variable is one that can be read from anywhere in the program. You can access these variables both inside and outside of the code. We declare a variable as global when we intend to use it across the rest of the program.
Example
The above example shows how we declared a variable called str outside of the function. When the function demo is invoked, the value of the variable str is printed. The global keyword is not required to use a global variable inside a function.
def demo(): print(Str) # Global Str = "Hello World" demo()
The output generated is as follows -
Hello World
Enclosing or Nonlocal Scope
The variable that is specified in the nested function is known as a Nonlocal Variable. It indicates that the variable cannot be both local and global in scope. The nonlocal keyword is used to generate nonlocal variables.
Example
The inner function is nested inside the outer function that we generated in the following example. Inner() function is defined in the outer() function's scope. Changes made to the nonlocal variable declared in the inner() function are mirrored in the output of the outer function.
def Outer(): x = "local" def Inner(): nonlocal x x = "nonlocal" print("inner:", x) Inner() print("outer:", x) Outer()
The output is as follows -
inner: nonlocal outer: nonlocal