Local Variable
Example:
#Local Variables:
print("============================")
print("Local Variables:")
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c = a + b
print("The sum is:", c)
# Calling a function
add()
OUTPUT:
Local Variables:
The sum is: 50
Note:
If you are given,
add()
print(a)
it will give error: The sum is: 50
print(a)
NameError: name 'a' is not defined
=============================================================================================
Global Variables
#Global Variables:
print("============================")
print("Global Variables:")
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Javatpoint'
print(x)
mainFunction()
print(x)
OUTPUT:
Global Variables:
101
Welcome To Javatpoint
Welcome To Javatpoint