python 传参 a=b_python函数之传参

函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

函数具有,可重复性,易维护性,提高开发效率等等。

>>>

>>> deffun1(a,b):print(a+b)>>> fun1(1,2)3

>>>

以上代码是一个简单的函数定义与使用案例。

①:位置参数

>>> deffun(a,b,c):print(a)print(b)print(c)>>> fun(1,2,3)1

2

3

>>> fun(1,2)

Traceback (most recent call last):

File"", line 1, in fun(1,2)

TypeError: fun() missing1 required positional argument: 'c'

>>> fun(1,2,3,4)

Traceback (most recent call last):

File"", line 1, in fun(1,2,3,4)

TypeError: fun() takes3 positional arguments but 4were given>>>

由上代码可知位置参数必须一一对应,不能少传参或多传参。

②:关键字传参

>>> deffun(a,b,c):print(a)print(b)print(c)>>> fun(a=1,c=3,b=2)1

2

3

>>> fun(a=1,c=3)

Traceback (most recent call last):

File"", line 1, in fun(a=1,c=3)

TypeError: fun() missing1 required positional argument: 'b'

>>> fun(a=1,c=3,b=2,d=4)

Traceback (most recent call last):

File"", line 1, in fun(a=1,c=3,b=2,d=4)

TypeError: fun() got an unexpected keyword argument'd'

>>>

由上代码可知,关键字传参无须一一对应,但任然不可少传参及多传参。

③:混合传参

>>> deffun(a,b,c):print(a)print(b)print(c)>>> fun(1,2,c=3)1

2

3

>>> fun(a=1,2,3)

SyntaxError: positional argument follows keyword argument>>> fun(1,b=2,3)

SyntaxError: positional argument follows keyword argument>>> fun(1,3,b=2)

Traceback (most recent call last):

File"", line 1, in fun(1,3,b=2)

TypeError: fun() got multiple valuesfor argument 'b'

由上代码可知混合传参,关键字参数只能位于左边,且要求一一对应,不可少传参及多传参。

④:默认传参

>>> def fun(a,b=2):print(a+b)>>> fun(1)3

>>> fun(1,3)4

>>>

由上代码可知,当不给b形参传值时,会使用默认值2,否则使用传递的参数。

⑤:参数组 *args,**kwargs

*args使用举例

>>> def fun(a,*args):print(a)print(args)>>> fun(1)1()>>> fun(1,2,3,4,5,6,7,8)1(2, 3, 4, 5, 6, 7, 8)>>> fun(1,(2,3,4,5,6,7,8))1((2, 3, 4, 5, 6, 7, 8),)>>> fun(1,*(2,3,4,5,6,7,8))1(2, 3, 4, 5, 6, 7, 8)>>>

由上代码可知,当不给*args传参时,args默认为空元组,第一个参数传值给第一个形参之后,后面的数据以逗号为分割为args的元组数据,在序列前加*则迭代成为args的元素元组。

**kwargs使用举例

>>> def fun(a,**kwargs):print(a)print(kwargs)>>> fun(1,b=2,c=3)1{'b': 2, 'c': 3}>>> fun(1,2,3,d=4)

Traceback (most recent call last):

File"", line 1, in fun(1,2,3,d=4)

TypeError: fun() takes1 positional argument but 3were given>>> fun(1,1,2,2,2,2,2,y=2,z=3)

Traceback (most recent call last):

File"", line 1, in fun(1,1,2,2,2,2,2,y=2,z=3)

TypeError: fun() takes1 positional argument but 7were given>>> fun(1,b=2,c=3,d=4,c=2)

SyntaxError: keyword argument repeated

由上代码可知,给**kwargs传值时,必须使用赋值模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值