python基础(七):函数

一、参数

1.参数分类:必备参数、关键字参数、默认参数、不定长参数

必备参数:

def function(a, b):
    print('I am %s, living on %s.'%(a, b))
    
function('rose', 'titanic') # output:I am rose, living in titanic.
function('rose')  # output:会报错
function('titanic', 'rose') # output:I am titanic, living in rose.

关键字参数:

function(b = 'titanic', a = 'rose')
# output:I am rose, living in titanic. 此时顺序就不会反
function(b = 'titanic', 'rose')
# 报错output:positional argument follows keyword argument

默认值参数:

定义函数时给形参赋值。默认参数必须在必备参数或关键字参数后面。

def function(a, b = 'titanic'):
    print('I am %s, living on %s.'%(a, b))
function('titanic')
# output:I am titanic, living on titanic.

不定长参数:

接受剩余的参数

def function(a, b, *c):
    print('I am %s, living on %s.'%(a, b))
    print(c)

function('rose', 'titanic', 1, 2, 3, 4)
# output:
# I am rose, living on titanic.
# (1, 2, 3, 4) # 默认记为元祖

*c 接受所有未命名的参数(关键字)

**d 接受所有命名的参数(带关键字的) 

def function(a, b, *c, **d):
    print('I am %s, living on %s.'%(a, b))
    print(c)
    print(d)

function('rose', 'titanic', 1, 2, 3, 4, age = 18)
# output:
# I am rose, living on titanic.
# (1, 2, 3, 4)
# {'age': 18}

# 带‘=’的接受为字典
# *c必须在**d之前,不然会报错
# 1,2,3,4必须在age = 18之前,顺序不能乱

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值