Python Programming – Scope and Lifetime of Variables
The scope of a variable can either be local or global. It is a region of the program, where it is recognized. If a variable is defined outside all the functions of a program then its scope is considered to be global. As the value of that variable can be accessed by any of the functions. Such a variable is termed a global variable. On the other hand, the local variable exhibits a limited scope. Any variable defined inside a function is referred to as a local variable as it can be accessed only within that function.
The lifetime of a variable is the duration or period for its existence in the memory. The lifetime of a local variable is as long as that function executes. They are destroyed or removed from the memory once the function is returned back to the function call. On the other hand, the lifetime of a global variable is as long as the whole program executes.
The program is given in Code: 6.15. illustrates the concept of local and global variables. In this program, we see that a variable value is defined globally with a value 0. A function call scope(lO) is made with argument 10. From the output, it is perceived that inside the function definition of scope() it prints 10 and after the function call it prints 0. It apparently signifies that the scope of variable val inside function definition is local whereas after the function call statement the value is printed out to be 0, i.e., the value is taken up from the global variable.
Code: 6.15. Illustration of global and local variables.
|# This program illustrates local and global variables
val=0 # global variable defined