Localglobalnonlocalvariables
Localglobalnonlocalvariables
1.Local Variables
2.Global Variables
3.Nonlocal Variables
Python Local Variables
When we declare variables inside a function, these variables will
have a local scope (within the function). We cannot access them
outside the function.
# local variable
message = 'Hello'
print('Local', message)
greet()
Output
Local Hello
NameError: name 'message' is not defined
Here, the message variable is local to the greet() function, so it
can only be accessed within the function.
That's why we get an error when we try to access it outside the
greet() function.
To fix this issue, we can make the variable named message
global.
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
Output
Local Hello
Global Hello
This time we can access the message variable from outside of the
greet() function. This is because we have created the message
variable as the global variable.
# declare global variable
message = 'Hello'
Now, message will be accessible from any scope (region) of the
program.
# nested function
def inner():
message = 'nonlocal'
print("inner:", message)
inner()
print("outer:", message)
outer()
Output
inner: nonlocal
outer: nonlocal
In the above example, there is a nested inner() function. We have
used the nonlocal keywords to create a nonlocal variable.