形式参数:
位置形参:
def 函数名(名称1,名称2):
默认形参:
def 函数名(名称1=数据1,名称2=数据2):
星号元组形参:
def 函数名(*args)
双星号字典形参:
def 函数名(**kwargs)
命名关键字形参:
def 函数名(*args,名称)
def 函数名(*,名称)
实际参数:
位置实参:
函数名(数据1,数据2)
序列实参:
函数名(*序列)
关键字实参:
函数名(名称1=数据1,名称2=数据2)
字典实参:
函数名(**字典)
1 函数形参
1.1 位置形参
def func01(p1,p2,p3): # p1,p2,p3 就称为位置形参
print(p1)
print(p2)
print(p3)
func01(1,2,3)
"""
输出结果:
1
2
3
"""
# func01(1)
# TypeError: func01() missing 2 required positional arguments: 'p2' and 'p3'
# 按位置对应,很明显传参的时候少传了两个数据,因此报错
1.2 默认形参
def func01(p1,p2,p3 = 3): # p3是默认形参
print(p1)
print(p2)
print(p3)
func01(2,3) # 2,3分别按位置对应p1,p2 称为位置实参。p3不传,默认值是3
"""
输出结果:
2
3
3
"""
1.3 单星号元组形参
避免用容器存储多个数据,而是用Python解释器自动把多个数据合在一起放在元组中
def func01(*args): # arguments
print(args)
func01(1,2,3)
func01(1)
func01()
"""
输出结果:
(1, 2, 3)
(1,)
()
"""
def mutiplicative(*args):
result = 1
for item in args: # args = ((1,2,3,4,5),)
result*=item # item = (1,2,3,4,5)
return result # result = 1 * (1,2,3,4,5)
print(mutiplicative((1,2,3,4,5)))
# 若不用*修饰形参,则需要将传入的数据用容器存储起来:[1,2,3,4,5]
"""
输出结果:
(1, 2, 3, 4, 5)
"""
1.4 双星号字典实参
def func01(**kwargs): # key word arguments
print(kwargs)
func01(a = 1,b = 2)
func01(a = 1)
func01()
"""
输出结果:
{'a': 1, 'b': 2}
{'a': 1}
{}
"""
1.5 命名关键字形参
def func01(*args,p): # p就是命名关键字形参,要用关键字实参传递数据
print(args)
print(p)
# func01(1,2,3) -- 这句话会报错,因为Python会默认将这几个数存储在一个元组args内,p没有收到数据
# TypeError: func01() missing 1 required keyword-only argument: 'p'
func01(1,2,p = 3) # p = 3,即按照关键字实参的方式传递数据
"""
输出结果:
(1, 2)
3
"""
2 函数实参
2.1 位置实参
def func01(p1,p2,p3):
print(p1)
print(p2)
print(p3)
func01(1,2,3) # 1,2,3为位置实参,按位置相对应位置的形参传入数据
"""
输出结果:
1
2
3
"""
2.2 关键字实参
def func01(p1 = 1,p2,p3 = 3): # p3就是默认形参,可不传
print(p1)
print(p2)
print(p3)
func01(p2 = 2) # 指定给p2传2这个数据,所以p2 = 2这就是关键字实参
"""
输出结果:
1
2
3
"""
func01(2,4,5)
"""
输出结果:
2
4
5
"""
2.3 序列实参
def func01(p1,p2,p3):
print(p1)
print(p2)
print(p3)
list01 = [1,2,3]
tuple01 = (1,2,3)
# name = "齐天大圣孙悟空"
# TypeError: func01() takes 3 positional arguments but 7 were given
# 拆序列,传元素,按顺序和形参对应
name = "孙悟空"
func01(*list01)
func01(*name)
func01(*tuple01)
"""
输出结果:
1
2
3
孙
悟
空
1
2
3
"""
2.4 字典实参
def func01(p1,p2,p3):
print(p1)
print(p2)
print(p3)
dict01 = {"p2":2,"p1":1,"p3":3}
func01(*dict01) # 传*dict01,则输出p2,p1,p3,即输出字典的键,**dict01——> 字典键和形参对应,输出值
"""
输出结果:
1
2
3
"""