# 形参,位置参数
def calc(x, y):
"形参是x和y"
res = x**y
return res
c = calc(5, 10) #5和10是实参,同时也可以考虑为位置参数
print(c)
#关键字参数
def calc2(x, y):
res = x**y
return res
x = calc2(y=8, x=10) #关键字参数,传值得时候加上参数的值,一一对应,不能缺
print(x)
#位置参数和关键字参数混搭
def calc3(x, y, z):
res = (x**y) * z
return res
#位置参数必须在关键字参数左边
y = calc3(9, 9, z=8)
print(y)
#默认参数
def calc4(x, y=2):
"默认参数为默认情况下指定参数"
res = x**y
return res
z = calc4(5) #传值的时候可以不传默认参数
w = calc4(5, 3) #也可以传值用位置参数覆盖默认参数
t = calc4(x=8, y=2) #也可以用关键字参数覆盖
print(z)
print(w)
print(t)
#参数组,非固定长度的参数,也叫收集参数
li_one = ['one', 'two', 'three', 'four', 'five']
dic_one = {'one': 1, 'two': 2, 'three': 3}
def test(x, *args, **kwargs):
print(x)
print(args) #可以不传,空元组
print(kwargs) #可以不传,空字典
test(1) #1被x接收
test(1, 2, 3, 4, 5, 6) #1被x接收,2,3,4,5,6被*args接收
test(1, 2, 3, 4, 5, 6, a=7, b=8, c=9) #1被x接收,2,3,4,5,6被*args接收
test(1, *[1, 2, 3, 4, 5, 6], **{'a': 7, 'b': 8, 'c': 9})
test(1, *li_one, **dic_one)