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