Local & Global variables in Python
In this post we will see local and global variables in Python.
Local Variables
- The variables which are declared inside a function are local
variables - These variables have local scope, which means they cannot
be accessed outside of the function
Example
# Program to illustrate local variables
def show():
s="Hello world"
print(s) # variable can be accessed here
show()
print(s) # variable cannot be accessed here
check output here
Global Variables
- The variables which are declared outside a function are global
variables - These variables have global scope, which means they can
be accessed anywhere in the program
# Program to illustrate global variables
s="Hello world"
def show():
print(s) # variable can be accessed here
show()
print(s) # variable can be accessed here
check output here
Local & Global Variable with same name
# Program to illustrate global variables
s="Hello world"
def show():
s="Hello from another world"
print(s) # local variable will be displayed here
show()
print(s) # global variable will be displayed here