python学习笔记,视频day14-函数

函数

  优点

  1. 代码重用
  2. 保持一致性,易维护
  3. 可扩展性

  函数参数

    形参:调用时分配内存,调用结束时释放内存

    实参:占用内存

    位置参数一一对应,关键字参数

  总结:

    返回值数=0,None

    返回值数=函数名,返回函数返回值

    返回值数=其他,返回其他

  过程:就是没有返回值的函数

  补充:两个函数重名,调用最新的函数

  函数遇到return立马结束

  

def test(x):
    "The function definitions "
    y=2*x+1
    return y
a=test(3)
print(a)
# 结果
# 7

  

def test(x):
    "The function definitions "
    y=2*x+1
    return y
print(test)
# 结果,打印出内存地址
# <function test at 0x008D07C8>
#没有返回值就是None
def test01():
    msg="hello"
    print(msg)

def test02():
    msg="hello2"
    print(msg)
    return msg
t1=test01()
t2=test02()
print(t1)
print(t2)
# 结果
# hello
# hello2
# None
# hello2
def test01():
    msg="hello"
    print(msg)

def test02():
    msg="hello2"
    print(msg)
    return msg
def test03():
    msg="hello3"
    print(msg)
    return 1,2,43,{"name":"alex"}
t1=test01()
t2=test02()
t3=test03()
print(t1)
print(t2)
print(t3)

# 结果
# hello
# hello2
# hello3
# None
# hello2
# (1, 2, 43, {'name': 'alex'})

 函数参数

# 位置参数,一一对应,缺一不可,多一也不行
def test(x,y,z):
    print(x)
    print(y)
    print(z)
test(1,3,2)
# 结果
# 1
# 3
# 2
# 关键字参数,无须一一对应,缺一不可,多一也不行
def test(x,y,z):
    print(x)
    print(y)
    print(z)
test(x=1,z=3,y=2)
# 结果
# 1
# 2
# 3
# 混合使用,位置参数必须在关键字参数左边,位置参数必须一一对应
def test(x,y,z):
    print(x)
    print(y)
    print(z)
test(1,3,z=2)
# 结果
# 1
# 3
# 2
# 默认参数,提前赋值了
def handle(x,type=None):
    print(x)
    print(type)
handle(1)
# 结果
# 1
# None
def handle(x,type=None):
    print(x)
    print(type)
handle("hello",type="hi")
# 结果
# hello
# hi
# 位置参数
def handle(x,type=None):
    print(x)
    print(type)
handle("hello","hi")
# 结果
# hello
# hi

参数组:*列表,**字典

# 参数组:**字典,*列表
def test(x,*args):
    print(x)
    print(args)
    print(args[1])
test(1,22,34,5)
# 结果
# 1
# (22, 34, 5)
# 34
# 不传为空
def test(x,*args):
print(x)
print(args)
test(1)
# 结果
# 1
# ()
 
# 若为字典,当成元组中的一个元素
def test(x,*args):
    print(x)
    print(args)
test(1,{"name":22})
# 结果
# 1
# ({'name': 22},)
# 若为列表,当成元组中的一个元素
def test(x,*args):
    print(x)
    print(args)
    print(args[0][0])
test(1,["x","y","z"])
# 结果
# 1
# (['x', 'y', 'z'],)
# x


#
*["x","y","z"],将列表遍历一遍依次赋值;["x","y","z"]表示当初一个列表当成一个整体传给第一个元素
def test(x,*args):
    print('x')
print(args)

test(1,*["x","y","z"])
# 结果
# ('x', 'y', 'z')
 
# 一个参数不能传两个值
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,y=2,z=3)
# 结果
# 1
# ()
# {'y': 2, 'z': 3}
def test(x,*args,**kwargs):
    print(x)
    print(args)
    print(kwargs)
test(1,2,5,76,7,y=2,z=3)
# 结果
# 1
# (2, 5, 76, 7)
# {'y': 2, 'z': 3}

  

原文地址:https://www.cnblogs.com/ppll/p/11538046.html