In python, when you create variables, sometimes you create them inside a function, sometimes at the beginning of the program, so when you create a variable and place it at different places in the program, that refers to scope of a variable in python.
Table of Contents
Local scope in python :
Local scope: it is also called the function scope, when you use code blocks inside a function, this function contains the names you define inside the function. So variables can only reach the area where they are defined. Python supports local scope as well as global scope.
Def example() Num=1; Print( “the number is”, num) Example()
Global scope in python :
In the global scope the variables can be read from anywhere inside the program, they are declared to be used in the entire code. They can be accessed inside or outside a function.
Def example() Print(“str”) Str= “this is easy” Example()
Non local scope in python :
Nonlocal scope is when you define a variable inside a nested loop, a nested loop is a loop within a loop, it means variable is neither in local scope or global scope. And to declare this variable, we use the keyword nonlocal.
Built-in scope in python :
If a variable is not defined in local, global or nonlocal, then python looks for it in built-in scope. Like when we want to calculate pi square value, we can use the built in variables.
The scope of a name or variable depends on the place in your code where you create that variable. Python follows a rule of LEGB which Is an acronym for Local, Enclosing, Global, and Built-in scopes. Python is a dynamically-typed language, variables in Python come into existence when you first assign them a value.
The LEGB rule is a kind of name lookup procedure, which determines the order in which Python looks up names. For example, if you reference a given name, then Python will look that name up sequentially in the local, enclosing, global, and built-in scope. If the name exists, then you’ll get the first occurrence of it. Otherwise, you’ll get an error.
In this article we saw scoop in python i.e. Built-in scope Global scope Local scope Non local scope so about this section you have any query then free to ask me
Name of the Intern who share this article :
St Joseph’s College / Bangalore University