Global vs. Local variables

  1. 定義在函式內的變數區域 (local) 變數,只限函式內存取;定義在函式外的全域 (global) 變數,則整個程式都可存取。
    [dywang@deyu zzz]$ cat function7.py
    #!/usr/bin/python3
    # coding: utf-8
    
    total = 0; # This is global variable.
    # Function definition is here
    def sum( arg1, arg2 ):
    	# Add both the parameters and return them."
    	total = arg1 + arg2; # Here total is local variable.
    	print("Inside the function local total :", total)
    	return total;
    
    # Now you can call sum function
    sum( 10, 20 );
    print("Outside the function global total :", total)
    
  2. 執行結果:函式內的區域變數 total=30,函式外的全域變數 total=0。
    [dywang@deyu zzz]$ ./function7.py 
    Inside the function local total : 30
    Outside the function global total : 0
    
  3. 設定 global 變數 total 為 sum 函式的回傳值。
    [dywang@deyu zzz]$ cat function7a.py
    #!/usr/bin/python3
    # coding: utf-8
    
    total = 0; # This is global variable.
    # Function definition is here
    def sum( arg1, arg2 ):
    	# Add both the parameters and return them."
    	total = arg1 + arg2; # Here total is local variable.
    	print("Inside the function local total :", total)
    	return total;
    
    # Now you can call sum function
    total = sum( 10, 20 );
    print("Outside the function global total :", total)
    
  4. 執行結果:函式內的區域變數 total=30,函式外的全域變數 total=30。
    [dywang@deyu zzz]$ ./function7a.py 
    Inside the function local total : 30
    Outside the function global total : 30