def 函數名([參數1, 參數2, ...]) : ''' 說明文檔 ''' 函數體 [return [返回值]]
函數名([實參列表])
# 定義一個函數 def girth(width, height): print("width:", width) print("height:", height) return 2 * (width + height) # 傳統調用函數的方式,根據位置傳入參數 print(girth(3.5, 4.8)) # 根據關鍵字傳入參數 print(girth(width = 3.5, height = 4.8)) # 使用關鍵字參數時可交換位置 print(girth(height = 4.8, width = 3.5)) # 部分使用關鍵字,部分使用位置參數 print(girth(3.5, height = 4.8))
def (say_hi(name = "alex")): print("Hi ", name)
def test(*names, **scores): print(names) print(scores) test("alex", "jack", 語文=89, 數學=94) """ 輸出結果: ('alex', 'jack') {'語文': 89, '數學': 94} """
def test(name, message): print(name) print(message) my_list = ['alex', 'Hello'] test(*my_list) # 使用逆向參數時,在實參前加上*號 my_dict = {'name': 'alex', 'message': 'hello'} test(**my_dict) # 使用字典時,在實參前加上兩個*號
Python規定:在函數內部能夠引用全局變量,但不能修改全局變量的值python
global
來聲明全局變量name = 'Charlie' def test(): print(name) global name name = "Alex" test() print(name)
在函數中定義函數形參,這樣便可在調用該函數時傳入不一樣的函數做爲參數,從而動態改變函數體的代碼app
def map(data, fn): result = [] for e in data: result.append(fn(e)) return result def square(n): return n * n def cube(n): return n * n * n data = [3, 4, 9] print("計算列表元素中每一個數的平方") print(map(date, square)) print("計算列表元素中每一個數的立方") print(map(data, cube))
def get_math_func(type): # 定義局部函數 def square(n): return n * n def cube(n): return n * n * n if type == 'square': return square elif type == 'cube': return cube # 調用get_math_func(),程序返回一個嵌套函數 math_func = get_math_func('square') print(math_func(3)) math_func = get_math_func('cube') print(math_func(3))
lambda [參數列表]: 表達式 即: def add(x, y): return x + y 可改寫爲: lambda x, y: x + y
Python要求lambda表達式只能是單行表達式函數
def get_math_func(type): if type == 'square': return lambda n: n * n elif type == 'cube': return lambda n: n * n * n