What are the local and global variables in python?
When a variable has a local scope or boundary beyond which you cannot use that variable for example if a variable can be only used within a function or module is known as a local variable.
On the other hand, if you want to use the same variable throughout the program then you declare it a global variable. You can use a global variable in more than one module or function.
Let’s understand the difference between these 2 variables using below program:
#Declare a variable
a = 100
#Defining a function
def local():
a = 'I am a local variable'
print(a)
#Calling a function
local()
#Printing variable "a" value
print(a)
In above program if you call function local() then value “I am a local variable” will be printed because variable a is declared within function and its scope is within local() function and that is the reason when you call print(a), it will return “100”.