Python3函數和lambda表達式

函數入門

定義函數和調用函數

  • 定義函數
def 函數名([參數1, 參數2, ...]) :
	'''
	說明文檔
	'''
	函數體
	[return [返回值]]
  • 調用函數
函數名([實參列表])

多個返回值

  • 若是程序須要多個返回值,則便可將多個值包裝成列表以後返回,也能夠直接返回多個值,Python會自動將多個返回值封閉成 元組

函數的參數

關鍵字(keyword)參數

# 定義一個函數
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表達式

語法

lambda [參數列表]: 表達式

即:
def add(x, y):
	return x + y
可改寫爲:
lambda x, y: x + y

Python要求lambda表達式只能是單行表達式函數

修改上例局部函數使用lambda表達式

def get_math_func(type):
	if type == 'square':
		return lambda n: n * n
	elif type == 'cube':
		return lambda n: n * n * n
相關文章
相關標籤/搜索