Local and global variables
Variables that are introduced in the main program are called global (or shared).
You can access global variables from any subroutine.
It is often necessary to introduce additional variables that will only be used in the subroutine. Such variables are called
local (or local). You can work with them only inside the subroutine in which they are created. The rest of the routines don't "know" anything about them.
Thus, it is possible to limit the scope (scope) of a variable only to the subroutine where it is really needed. In programming, this technique is called
encapsulation - hiding the variable from being changed from outside.
Analyze three programs:
Description |
Program |
1) In this program, the variable i is local. If there is no i variable in the main program, then we will get an error message. And if there is such a variable (then it is a global variable), then its value is displayed on the screen. |
def test():
print(i)
|
2) Here, even if there is a global variable i , a new local variable i will be created with a value of 2, and 2 will appear on the screen. |
def test():
i = 2
print(i)
|
3) In this program, there is a global variable i with a value of 15. Its value can be changed inside the subroutine, for this it is necessary to explicitly declare that it is global (use the command global ).
The procedure will work with the global variable i and it will be assigned a new value of 2. The value 2 is displayed. |
def test():
global i
i = 2
# main program
i = 15
print(i)
|