import builtins # Overview and application of scope global_scope = 0 # Global scope # Define a local scope in a closure function def outer(): o_count = 1 # In a function other than a closure function , Relative to the function inner() Come on Scope nonlocal def inner(): local_scope = 2 # Local scope # Check which variables are introduced into the module print('builtins The variables introduced in the module are :%s' %dir(builtins)) # # Variable access in other modules name1 = 'SuSan' if('SuSan'.__eq__(name1)): result = 'I am SuSan,I am from China' else: result = 'I am from USA' print(result) # If you define a variable inside a function , Then the external cannot access def names(): name2 = 'SuSan' # if('SuSan'.__eq__(name2)): result1 = 'I am '+name2 +','+'I am from China' # else: result1 = 'I am from USA' # print(result1) # Global and local variables total = 0 # This is a global variable # Function description def sum(arg1, arg2): # return 2 The sum of parameters ." total = arg1 + arg2 # total Here is the local variable . print(" Function is a local variable : ", total) return total # call sum function , The calculation result of the passed in parameter shows the local variable sum(10, 20) print(" Outside the function is the global variable : ", total) # Use golbal Keyword to access and modify global variables num = 1 def fun1(): # Declare access to global variables global num # Need to use global Keyword declaration # Output the original value of the global variable print(num) # Modify global variables num = 123 print(num) # Call function fun1() # Output the modified global variable value print(num) # Use nonlocal Keyword to declare variables and modify # Defined function def outer(): # Defining variables num = 10 # Defining nested functions def inner(): nonlocal num # nonlocal Keyword declaration , Using variables in functions # Change the value of the variable num = 100 print(num) inner() print(num) outer() # Under special circumstances b = 8 def test(b): b = b * 10 print(b) test(b) b = 8 def test(): global b b = b * 30 print(b) test()
Preface In the article of the
如果你打開“摩托范”網頁,You will see the