There are two main types of Python variables: local and global variables.
Local variables are defined inside a function and can only be accessed within that function. Global variables are defined outside of any function and can be accessed from anywhere in the program The scope of a variable is determined based on where it is defined.
In the same program you can have same name for local and global variable and they both contains different values.
** This example will explain the scope of variables**
area_name = "India"
def sample_function():
area_name= "Pune"
print("*** Inside function : ",area_name)
print("*** Before calling function : ", area_name)
sample_function()
print("*** After calling function : ", area_name)
** If you have not defined variable in function, you can still access global variable, however you can not modify it. If you modify, the changes are relevant in the function only.
area_name = "India"
def sample_function():
print("*** Inside function : ",area_name)
print("*** Before calling function : ", area_name)
sample_function()
print("*** After calling function : ", area_name)
*If you want to modify global variable inside function, you need to use keywork global inside function
area_name = "India"
def sample_function():
global area_name
area_name= "Pune"
print("*** Inside function : ",area_name)
print("*** Before calling function : ", area_name)
sample_function()
print("*** After calling function : ", area_name)
d.
post by Pravin