函数参数传递

函数的参数传递

1. 参数定义与传递的基本顺序

位置参数——>关键字参数——>可变数量参数

  • 位置参数
    根据位置传递的参数
>>> def add(x,y):
>>> 	return x + y
>>> add(3,4)
7
  • 关键字参数
    根据关键字传递的参数
>>> def add(x,y):
>>> 	return x + y
>>> add(y = 4,x = 3)
7
  • 可变数量参数
    1.arg:以元组形式返回
    2.**arg:以
    字典形式返回
>>> def test_fun(a,b = 6,*c,**d):
>>>    print("a = ",a,"b = ",b,"c = ",c,"d = ",d)
>>> test_fun(1)
a =  1 b =  6 c =  () d =  {}
>>> test_fun(1,2)
a =  1 b =  2 c =  () d =  {}
>>> test_fun(1,2,3)
a =  1 b =  2 c =  (3,) d =  {}
>>> test_fun(1,2,3,4)
a =  1 b =  2 c =  (3,4) d =  {}
>>> test_fun(a = 1)
a =  1 b =  6 c =  () d =  {}
>>> test_fun(a = 1,b = 2,c = 3) #c和d是占位符,不是名称,c是不确定数量的单个变量,d是有键有值
a =  1 b =  2 c =  () d =  {'c': 3}
>>> test_fun(1,2,3,4,x = 1)
a =  1 b =  2 c =  (3,4) d =  {'x': 1}
>>> test_fun(1,2,3,4,5,6,x = 1,y = 2,z = 3)
a =  1 b =  2 c =  (3, 4, 5, 6) d =  {'x': 1, 'y': 2, 'z': 3}
>>> test_fun(1,2,3,4,b = 8) #b不能二次赋值
TypeError: test_fun() got multiple values for argument 'b'

2. 函数的定义

 def 函数名([参数列表]):
	 函数体

注:’’‘可以用来注释’’’

>>> def fun():
>>>    '''This is a function
>>>    it will realize some function'''
>>>    print('Hi,welcome to my function')
>>> help(fun)
fun()
    This is a function
    it will realize some function
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值