一、语法构造
def 函数名(形参):
‘’‘
注释(可省略,最好写一下)
‘’’
函数体语句
return 返回值
例:
def test(x): #有形参
'''
:param x: 整形数字
:return:返回计算结果
'''
y = 2 * x + 1
return y
res = test(2) #调用函数,实参为2,返回值赋值给res
print(res) #5
def test(): #无形参
'''
:param x: 整形数字
:return:返回计算结果
'''
x = 2
y = 2 * x + 1
return y
res = test() #调用函数,返回值赋值给res
print(res) #5
过程:就是没有返回值的函数
def test():
print('hello world')
res = test()
print(res)
'''
hello world
None
'''
二、函数返回值
(1)无返回值,则返回None
(2)一个返回值,返回对象本身。
(3)多个返回值,将返回值组合成元组返回。
(4)函数语句遇见return语句,即停止运行。
def test1():
pass
def test2():
msg = 11
return msg
def test3():
a = 'abc'
b = (1,2,3)
return a,b
print(test1()) #None
print(test2()) #11
print(test3()) #('abc', (1, 2, 3))
三、函数参数
1、位置参数
注:必须一一对应,缺一不行多一也不行
def test(a, b, c):
return a, b, c
print(test(1, 2, 3)) #(1, 2, 3)
2、关键字参数
注:无须一一对应,缺一不行多一也不行
def test(a, b, c):
return a, b, c
print(test(b=2, c=3, a=1)) # (1, 2, 3)
3、位置参数和关键字混合
注:位置参数必须在关键字参数左边,并且位置参数赋值后,关键字参数不能重复赋值
4、参数可以赋默认值
def test(a, b=2):
return a, b
print(test(1,3)) #(1, 3)
print(test(1)) #(1, 2)
5、参数组
(1)实参位置
①* 将一个元组或列表中的元素按位置参数传递
②** 将一个字典的元素按关键字参数传递
(2)形参位置
①* 将位置参数组装成一个元组
②** 将关键字参数组装成一个字典
def test1(*args,**kwargs):
print(args,kwargs)
test1(1,3,2,k1='aa',k2='bb') #(1, 3, 2) {'k1': 'aa', 'k2': 'bb'}
test1([1,2,3],{'k1':11}) #([1, 2, 3], {'k1': 11}) {}
test1(*[1,2,3],*(1,2),**{'k1':11}) #(1, 2, 3, 1, 2) {'k1': 11}