Scopes in Python
Last updated Aug 10, 2021Scopes in Python
In Python Programming language variables that can only reach the area in which they all are defined are known by the term of scope.
As you can easily understand from the word scope, that it means range or extent. So in Python Programming language, we use a scope to access and call variables for a selected region or a selected range of code. The scope concept in python is generally presented using a rule which is known as the LEGB rule which stands for Local, Enclosing, Global, and Built-in scopes.
Types of scopes in Python
There are two types of scope in the Python Programming language. They are stated below:-
-
Local Scope
-
Global Scope
Both these scopes have different roles and are used at different times according to the needs of the program. Now we will understand when and how to use both the scopes i.e. Local Scope and Global Scope.
Local Scope
A variable in python is created inside a function and it belongs to the local scope of that function. And the function inside the scope can be used only inside the function. Let's take an example of Local scope:-
def func1(): x = 10 def func2(): print(x) func2() func1() |
10 |
So the value of x is local for func1 and it can be easily used inside a function so we get the output as 10 which is the value of x because x is a local variable and can be accessed locally but only in the same function.
Global Variable
Global Scope in Python contains a Global Variable which is created in the main body of the python code. Global variables are available from within any scope, global and local. You can call a global function when you want to implement it and use it as per your program need. Let's understand better about Global scope using an example:-
x = 10 def func1(): print(x) func1() print(x) |
10 |
10 |
So as you can see that we got the following output and here x acts as a global variable and it has executed in the function and even after the function and this is the function of global scope that you can call the global variable throughout the program instead of calling inside the function.
Article Contributed By :
|
|
|
|
68 Views |