Global vs. local variables
1. Variables defined in subroutines are called local variables, and variables defined at the beginning of a program are called global variables.
2, the scope of global variables is the entire program, the scope of the local variable is the subroutine that defines the variable.
3. When the global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.
Example one: (local variable)
def changename (name): print ("Change before", name) name = "Robin Wen" #这个函数就是这个变量的作用域, this variable only takes effect in this function = = >> local variable print ("Change after", name) name = "Robin" ChangeName (name) print
#我们使用上面的函数将robin传入函数中进行修改为Robin Wen, but the effect of the final output is still robin.
Output Result:
Change before Robin
Change after Robin Wen
Robin
Example two: (global variable)
Referencing global variables in a function program
School = "Oldboy" Def Stu (): Global School Print ("Before the school is:", school) school = "BJ" Stu () print (" After the school is: ", school)
Python local variables and global variables scope--021