Function Local Variables Global Variables and Their Scope
# Relationship between local and global variables and their scopes for variables of simple types (int str, etc.) name = "xxx" # Variables defined at the top of the first level are called global variables, and their scope begins at the location where the variable is defined and ends at the end of this program def Print_Name(): print("name before change:", name) #Since name has been defined as a global variable before this function, the function here reads the variable name as the global variable name "xxx", and the function can no longer define a local variable with the same name, otherwise it is impossible to distinguish whether the variable is a local variable or a global variable. # name = "yyy" #This statement will report an error when it is released:IndentationError: unindent does not match any outer indentation level Print_Name() def Change_Name(): name = "yyy" # A local variable with the same name as a global variable is first defined inside a function, then the entire function operates internally as a local variable (a temporary variable with the same name as the global variable) print("name after change is", name) Change_Name() # yyyy actually outputs the value of the local variable print("global name is", name) # xxx Global variables are accessed here because this print statement is not inside Change_Name. # The function needs to force changes to global variables internally, using the global keyword def Change_global_Name(): global name print("name before change is :", name) name = "yyy" Change_global_Name() # xxx Global variables before modification print("global name is :", name) # yyyy Here, because name is forced to be declared as a global variable within the function, global can be manipulated throughout the function. # Complex data types lists collections dictionaries and other complex data structures if the function is defined externally inside the function can not use the global statement is also operated by the global variables, there is no local variables a say! names = ['111', '222', '333'] def Change_Names(): names[0] = "444" print("in function names :", names) Change_Names() #in function names : ['444', '222', '333'] print("global names :", names) #in function names : ['444', '222', '333'] For complex data types,Manipulating global variables directly within a function,No more local variables will be generated
recursive (calculation)
# Functions can call other functions internally, if a function calls itself internally it is called a recursive function def Half_fun(n): print(n) if n < 2: return n Half_fun(n/2) Half_fun(100) #Recursive properties:1、There must be a clear end condition 2、The problem complexity of each recursive call needs to be simplified compared to the last one 3、Recursion takes up a lot of memory
The above example is very simple, you can test it this time, thank you for reading and supporting me.