Python global variables and local variables and the application of global

Python global variables and local variables and the application of global

Variables declared outside the function are called global variables and can be accessed by all functions.
The variables declared in the function are called local variables , and the local variables are limited to the function.

Insert picture description here
Variables inside a function can be modified and assigned at will, but global variables cannot be modified in the function body. How to solve it?
The global variable name needs to be declared inside the function , as follows:
Insert picture description here
At this time, the global variable has been modified , and when func() is called again, the global variable name becomes the modified name of func1(), as follows:
Insert picture description here
Insert picture description here
when? How about adding global?

When the global variable is an immutable object (string), you need to add global
when you modify the global variable in the function. When the global variable is a variable object (list), you don’t need to add global when you modify the global variable in the function. ,as follows:
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44994799/article/details/109771334