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
相关文章
相关标签/搜索