Scope of the variables
Scope of the variable is resolved by LEGB rule in python
L - Local E - Enclosing function locals G - Global B - Built-in
Local
x = 25
def printer():
x = 50
return x
print(x)
>> 25
print(printer())
>> 50
Local
# Global
name = 'THIS IS A GLOBAL STRING'
def greet():
# Enclosing
name = 'Sammy'
def hello():
# Local
name = "I'm Local"
print('Hello '+name)
hello()
greet()
Result:
>> Hello I'm Local
Enclosing function locals
name = 'THIS IS A GLOBAL STRING'
def greet():
name = 'Sammy'
def hello():
print('Hello '+name)
hello()
greet()
Result:
>> Hello sammy
Global
name = 'THIS IS A GLOBAL STRING'
def greet():
def hello():
print('Hello '+name)
hello()
greet()
Result:
>> Hello THIS IS A GLOBAL STRING
built-in
>> len
>> help(len)
Global Keyword
Global keyword allows you to modify the variable outside of the current scope.
It is used to create a global variable and make changes to the variable in a local context.
The basic rules for global keyword in Python are:
- When we create a variable inside a function, it is local by default.
- When we define a variable outside of a function, it is global by default. You don't have to use global keyword.
- We use global keyword to read and write a global variable inside a function.
- Use of global keyword outside a function has no effect.
Modifying the Global variable from inside the function
Example
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
Result:
>> UnboundLocalError: local variable 'c' referenced before assignment
In order to modify the global variable from inside the function, we need to call the global variable inside the function.
Modifying the Global variable inside the function
c = 0 # global variable
def add():
global c
c = c + 2 # increment by 2
print("Inside add():", c)
add()
print("In main:", c)
Result:
>> Inside add(): 2
>> In main: 2