return語句
return [expression]語句退出一個函數,可選地將一個表達式傳回給調用者。沒有參數的return語句與return None相同。
變量范圍
變量的范圍決定了可以訪問特定標識符的程序部分。Python中有兩個變量的基本范圍:
全局變量
局部變量
全局與局部變量
在函數體內定義的變量具有局部作用域,外部定義的變量具有全局作用域。
局部變量只能在它們聲明的函數內部訪問,而全局變量可以通過所有函數在整個程序體中訪問。
當調用一個函數時,它內部聲明的變量被帶入范圍。
total = 0 # This is global variable.
def sum( arg1, arg2 ): total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total) return total sum( 10, 20 ) print ("Outside the function global total : ", total )
輸出:
Inside the function local total : 30 Outside the function global total : 0