小菜鸟的代码世界 2020-05-04
代码可以重复使用,提高代码的利用率
保持代码一致性,易维护
可扩展性
def function(x):
  ‘‘‘函数说明文档‘‘‘
    x += 1
    return expression
function(2)
# def:定义函数的关键字
# function:函数名
# ():括号内可以设置参数,形参
# x += 1:泛指代码块或程序处理逻辑
# return expression:定义返回值
# function(2):传入实参def greet(name):
    ‘‘‘打招呼函数‘‘‘
    mes = ‘hello %s !‘%name
    return mes
res = greet(‘alex‘)
print(res)
# =>hello alex !return [expression] 语句:退出函数,函数运行到return语句就是直接退出函数,不会再继续运行函数体内return下面的语句。return返回值。
<1> 默认返回值
默认返回值:在函数体内部若无return返回值,则默认返回None,return是函数结束的标志。
def greet(name):
    print(‘hello %s !‘%name)
print(greet(‘张三‘))
# =>hello 张三 !
# =>None有1个返回值:指定了返回值
def greet(name):
    print(‘hello %s !‘%name)
    return ‘你真棒!‘
print(greet(‘张三‘))
# =>hello 张三 !
# =>你真棒!多个返回值:指定了多个返回值,当有多个返回值时,以元组形式返回,内含多个值
def greet(name):
    print(‘hello %s !‘%name)
    return ‘你真棒!‘,‘Are you OK!‘,‘666‘
print(greet(‘张三‘))
# =>hello 张三 !
# =>(‘你真棒!‘, ‘Are you OK!‘, ‘666‘)def calc(x,y):  # x,y :形参
    result = x+y
    return result
c = calc(1,2) # 1,2:实参(具体数值)
print(c)
# =>3位置参数:传递的实参个数与形参必须一一对应,少一个和多一个都不行,不对应会报错
# 一一对应
def position(x,y,z):
    print(x)
    print(y)
    print(z)
position(1,2,3)
# =>1
# =>2
# =>3
# 不对应
def position(x,y,z):
    print(x)
    print(y)
    print(z)
position(1,2,3,4)
# =>报错关键字参数:对形参无需对应,但必须进行一一指定 ,少一个和多一个都不行,否则会报错
def key(x,y,z):
    print(x)
    print(y)
    print(z)
key(x=1,y=2,z=3)
# =>1
# =>2
# =>3位置和关键字参数混合使用:位置参数必须在左边也就是前边,关键字参数在后面,一一对应 关系,多个值会报错
def position_key(x,y,z):
    print(x)
    print(y)
    print(z)
position_key(1,2,z=3)
# =>1
# =>2
# =>3
position(1,y=2,3) 
# =>报错默认参数:定义了默认形参,实参就可以不用传递,若传递会覆盖默认参数
def default(x,type=‘King‘):   # type=‘King‘:为默认参数
    print(x)
    print(type)
default(‘hello‘)   # 不对默认参数进行传递
# =>hello
# =>King
default(‘hello‘,‘lisi‘)   # 对默认参数进行传递,会覆盖原有参数
# =>hello
# =>lisi参数组:(**字典;*列表)传递可变长参数
def test(x,*args):  # *:作为列表存储
    print(x)
    print(args)   # 作为元组输出
test(1,2,3,4,5)
# =>1
# =>(2, 3, 4, 5)
def test(x,**kwargs):  # **:作为字典存储
    print(x)
    print(kwargs)   # 作为字典输出
test(1,y=2,z=3)
# =>1
# =>{‘y‘: 2, ‘z‘: 3}
def test(x,*args,**kwargs):  # 可以接受多个值
    print(x)
    print(args)  # 作为元组输出
    print(kwargs)   # 作为字典输出
test(1,2,3,4,5,6,7,y=2,z=3)
# =>1
# =>(2, 3, 4, 5, 6, 7)
# =>{‘y‘: 2, ‘z‘: 3}
test(1,*[1,2,3],**{‘y‘:2,‘z‘:3})
# =>1
# =>(1, 2, 3)
# =>{‘y‘: 2, ‘z‘: 3}7)参数集合实例