A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable.
The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable.
When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables; global variables work elsewhere
Example 1:
def change_name (name):
Print ("Before Change", name)
Name= "Zhangyan" #这个函数就是这个变量的作用域
Print ("After Change", name)
Name= "Zhangyan"
Change_name (name)
Print (name)
Result: Name is still Zhangyan (reason: The local variable cannot modify the value of the global variable)
Example 2:
def change_name (name):
Age=28
Print (age)
Result: Error, age undefined
Example 3:
School= "Oldboy"
def change_name (name):
Global school #局部变量前加上global变为全局变量, you can modify the value of the same variable name outside the function
School= ' Mage Linux '
Print (school)
Result: School for "Mage Linux"
Getting started with Python: local variables