In Python, we cannot just access any variable from any part of our program. Some of the variables may not even exist for the entire duration of the program. In which part of the program we can access a variable in which parts of the program a variable exists depends on how the variable has been declared.
Scope of the variable
Part of the program in which a variable is accessible is called its scope.
Lifetime of the variable
Duration for which variable exists is called its lifetime.
Global variables are those variables which are defined in the main body of the program file. They are visible throughout the program.
A variable which is defined within a function is local to that function. A local variable can be accessed from the point of its definition until the end of the function in which it is defined. It exists as long as the function is executing. Function parameter behave like local variables in the function. Moreover, whenever we use the assignment operator (=) inside a function, a new local variable is created.
a=90 # global variable print("Global variable=",a) def func(num): # num as function parameter print("In Function-local variable num=",num) num1=70 # num1 is a local variable print("In Function-local variable num1=",num1) func(90) # 90 is passing as an argument to the function print(a) # Global variable is beign accessed print("num1 outside the function=",num1)
Global variable= 90 In Function-local variable num= 90 In Function-local variable num1= 70 90
Traceback (most recent call last)
File "C:/Users/User/AppData/Local/Programs/Python/Python38-32/eeeeeeee.py", line 9, in <module>
print("num1 outside the function=",num1)
NameError: name 'num1' is not defined
To define a variable defined inside a function as global, we must use a global statement. This declares the local or the inner variable of the function to have module scope.
var="Good" def display(): global var var1="Morning" print("In Function var is=",var) display()
In Function var is= Good
We can have a variable with the same name as that of a global variable in the program. In such a case a new local variable of that name is created which is different from the global variable.
var="Good" def show(): var="Morning" print("In Function var is=",var) show() print("Outside function is=",var)
In Function var is= Morning Outside function is= Good
If we have a global variable and then create another global variable using the global statement, then changes made in the variable is reflected everywhere in the program.
var="Good" def show(): global var var="Morning" print("In Function=",var) show() print("Outside function is=",var) var="Fantastic" print("Outside Function, after modification, var is=",var)
In Function= Morning Outside function is= Morning Outside Function, after modification, var is= Fantastic