A variable defined in a function is called a local variable, and a variable that defines a level of code outside the function is called a global variable.
Results:
Jakealex
Two variables are called name but they're not the same thing, they're irrelevant.
If a local variable with the same name as the global variable is not defined within the function, the global variable that can be called in the function is
name = ' Alex ' def Change_name (): #name = ' Jake ' print (name) change_name () print (name)
Results:
Alexalex
Summarize:
1, (Find call variable in function) Priority: Local variables > Global variables (if both global and local have a variable of the same name)
2, outside the function is unable to call the function within the variable (local variable), local variables can only be partially effective
3, in the function can refer to the global variables, but not the global variables, if you want to modify the global variables within the function instead of redefining a new local variable, it is necessary to use global (generally not recommended, because in this function changed the global variables, May affect other functions calling the global variable)
name = ' Alex ' def Change_name (): Global name #先声明 name = ' Jake ' #再修改, both order cannot be reversed print (name) Change_ Name () print (name)
Results:
Jakejake
3.1, the above example we just tested the string, to re-assign a string global variable to use global, but for the list, collection, dictionary, although cannot be re-assigned (without global premise), but you can re-modify the elements in it:
list = [' Alex ', ' Jake ', ' rain ']dict = {' Alex ': 1, ' Jake ': 2, ' rain ': 3}set = {1,2,3,4,5}def change_name (): list[1] = ' Cody ' dict[' jake '] = 4 set.remove (5) print (list) print ( dict) print (set) change_name () Print (list) print (dict) print (set)
Results:
['Alex','Cody','Rain']{'Alex':1,'Jake':4,'Rain':3}{1,2,3,4}['Alex','Cody','Rain']{'Alex':1,'Jake':4,'Rain':3}{1,2,3,4}
Because the list, the collection, the dictionary in the global variable has a memory address, the element inside has a memory address, when the variable is called, the whole memory address cannot be modified, but the memory address of each element inside can be modified.
Tuples themselves cannot be modified, but if a tuple contains lists, collections, dictionaries, those lists, collections, dictionaries can be modified
4, the string, the number, the Boolean cannot be directly, the list, the collection, the dictionary can be modified, the tuple sees the situation
python3--local variables and global variables