Pyton 函數呼叫
函數定義def function_name (a,b):
...
...
... return xxxxx
全域變數vs 區域變數
- 全域變數: 變數宣告在任何函數外,即為全域變數
- 區域變數: 定義在函數內部的變數, 非def 內無法存取此區域變數
- Python 函數可以直接存取(直接用或操作)全域變數 (不必傳參數)
- 小心: 若宣告區域變數與全域變數的名稱相同, 則以區域變數為主, 若函數內要使用外部的全域變數, 必須用global 關鍵字, 表示其參考外部的全域變數,而非重新定義的區域變數
# 全域變數vs 區域變數
x1=[2,4,6]
a=5
def func1():
x1[1]=100 #存取會更改x1
def func2():
x1=[1,2,3] #初值設定,宣告變數x1 (和global x1相同, 故此為Local Variable )
print(x1) #[1, 2, 3]
def func3():
a=10 #屬初值設定而非更改變數,因為是宣告, 則變數a為Local (雖然和global a相同
print(a)
def func4():
global a
a=10 #初值設定為local, 但global明確定義a是global
print(a) #10
def func5():
global x1
x1=[1,2,3] #初值設定:x1是local
func1()
print(x1) #[2, 100, 6]
func2()
print(x1) #[2, 100, 6]
func3()
print(a) #5
func4()
print(a) 10
func5()
print(x1) [1, 2, 3]
lambda Function
Python提供了一個簡易的function define:lambda,用完即丟,不著痕跡。讓你實作出很簡單的function (只處理一個運算式)
語法:
ambda argument_list: expression
def func(x, y, z):
return x + y + z
func2 = lambda x,y,z : x+y+z
print(func(1,2,3))
print(func2(1,2,3))
map Function
map() is a function which takes two arguments:
r = map(func, seq)
The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. Before Python3, map() used to return a list, where each element of the result list was the result of the function func applied on the corresponding element of the list or tuple "seq". With Python 3, map() returns an iterator.
my_list = [1, 2, 3]
ans=list(map( lambda i: i * i, my_list ))
print(ans)
[1, 4, 9]
不定個數參數函數用法
#不定個數參數 * (tuple)
def hello(*names):
for n in names
print("Hello, %s."%n)
names_tuple=("Tom","Peter","Bob","Rain")
hello(*names_tuple)
hello("Tom","Peter","Bob","Rain")
#不定個數參數 ** (dict)
def hello(**names):for n in names:
print("Hello %s, you're %d years old"%(n,names[n]))
names_dict={'John':25, 'Tom':20, 'Bob':33, 'Tony':18}
hello(**names_dict)
hello(John=25, Tom=20, Bob=33, Tony=18)