Scope of Variables in Python
Scope is a visibility which determines whether the variable is accessed by other parts of a code or not. Let’s see an example:
num = 5def func(x):
num=3
return numprint(num)
print(func(num))Output:
5
3
So, both print statements are printing the different results. This is what we call as Scope. Python has set of rules with which it decides what variables you are referencing in the code.
Scope can be described by LEGB rule:
- Local
- Enclosing funcrions
- Global
- Built-in
Examples of LEGB:
- Global variables:
Global variable is declared outside of the function or in global scope. When we define a variable outside of a function, it’s global by default. Global variable can be accessed inside function also.
# num is global herenum = 5def func():
print(num)print(num)
func()Output:
5
5
Let’s see one more example:
num = 5def func():
num += 2
print(num)print(num)
func()Output:
5
Traceback (most recent call last):
File "/home/main.py", line 15, in <module>
func()
File "/home/main.py", line 11, in func
num += 2
UnboundLocalError: local variable 'num' referenced before assignment
We are trying to change variable inside a function which is global. But, variables inside function are local by default and that’s why we got error here. We have to use global keyword to read and write a global variable inside a function.This can be solved by making the variable global explicitly as follows:
num = 5def func():
global num # making variable global explicitly
num+=2
print(num)print(num)
func()Output:
5
7
- Local Variables
When we create a variable inside a function, it’s local by default.
def func():
number =10
print(number)func()Output:
10
What if we try to access variable number outside a function ?
def func():
number =10
print(number)func()
print(number)Output:
10
Traceback (most recent call last):
File "/home/main.py", line 16, in <module>
print(number)
NameError: name 'number' is not defined
We are trying to print local variable ‘number’ in a global scope and hence we got error.
What if we use global variable and local variable name same?
num = 5def func():
num=3
print(num)print(num)
func()Output:
5
3
When we print the variable inside the func(), it outputs 3, i.e. local scope of variable.
Similarly, when we print the variable outside the fun(), it output 5, i.e. global scope of variable.
- Enclosing Functions
When we have function inside a function, this case may arise.
number = 5def func():
# Enclosing function
number=10
def func1():
print(number)
func1()func()Output:
10
10 is printed because func1() is enclosed inside func().
- Built in variables
Built-in means already defined in Python. Don’t assign these to another variable and don’t override these variables.
example, len is a built-in variable in Python.
print(len)Output:
<built-in function len>
That’s it!
Happy Coding!