定义函数的参数

本文详细介绍了Python函数参数的使用,包括位置参数、关键字参数、默认值、参数收集和字典转换。通过示例展示了如何定义和调用这些参数,并强调了参数分配的重要性。此外,还探讨了混合使用各种参数类型的情况,以及关键字参数在函数调用中的灵活性。
摘要由CSDN通过智能技术生成

位置参数

定义参数的顺序和调用参数传递值的顺序要一致

关键字参数

定义参数的时候设置一个默认值,当调用参数的时候不分配这个参数就会使用默认值
定义和调用的时候参数名要一致,顺序随便

def hello(greeting='hello',name='world'):
    print('{} {}!'.format(greeting,name))
hello(name='YI',greeting='handson')

运行结果:

handson YI!

Process finished with exit code 0

关键字参数的优点:对于不变的参数值可以在设置的时候设置默认值

参数收集

收集参数:定义参数的时候使用星号,def 函数名(参数A,*参数B):
传参的时候如果超过2个,多余的都会保存在参数B中,元组形式,只有一个参数的话,参数B会是个空元组
带两个星号:可以收集关键字参数,返回的是字典形式

def num1(x,*y,z):
    print(x,y,z)
def num2(x,**y):
    print(x,y)
num1(1,2,3,4,5,z=6)
num2(1,a=2,b=3)

运行结果:

1 (2, 3, 4, 5) 6
1 {'a': 2, 'b': 3}

Process finished with exit code 0

关键字参数–字典
单个参数–元组(列表)

参数分配

在调用函数的时候使用*是解包,把变量a的字典内容解包成关键字参数赋值给函数

a={'y':1,'x':2}
def add(x,y):
    return  x+y
s=add(**a)
print(s)
3

Process finished with exit code 0

字典–关键字参数
元组(列表)–单个参数
在函数调用的时候也可使用*,一个代表传递元组,两个代表传递字典
调用和分配的时候都使用*,和都不用是一样的效果
参考链接:https://www.jianshu.com/p/0ed914608a2c
这里直接把y指向的元组赋值给了add

def add(*args):
    x=0
    for i in args:
        x+=i
    print(x)
y=(1,3)
add(*y)

在这里插入图片描述

应用

#关键字参数
#关键字参数
def story(**param):
    print('{name} is {job}'.format_map(param))
story(name='yiyangqianxi',job='actor')
story(job='actor',name='yiyangqianxi')
data={'name':'yiyangqianxi','job':'actor'}
story(**data)  #字典转为关键字参数,关键字再转为字典
del data['job']
story(job='singger',**data)

运行结果:

yiyangqianxi is actor
yiyangqianxi is actor
yiyangqianxi is actor
yiyangqianxi is singger

Process finished with exit code 0
#位置参数
def power(x,y,*other):
    if other:
        print('{}!'.format(other))
    print(pow(x,y))
power(2,2,'yiyangqianxi')
a=(3,)*4
power(*a)          #元组转为多个参数,多个参数转为元组,

运行结果:

('yiyangqianxi',)!
4
(3, 3)!
27

Process finished with exit code 0

调用参数的时候,直接调用元组列表或者字典,不适用*会报错(定义参数的时候是有*的话)

#混合使用
def num(start,stop=0,step=1):
    if stop==0:
        start,stop=stop,start #互换
    result=[]
    i=start
    while i<stop:
        result.append(i)
        i+=step
    print(result)
num(10)

运行结果:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值