函数:逻辑结构化和过程化的一种编程方法

面向对象---》类 class

面向过程---》过程 def

函数编程---》函数def

import time
def logger():
    time_format='%Y-%m-%d %X'#格式化时间
    timecurrent=time.strftime(time_format)
    with open("log.txt","a+",encoding="utf-8") as f:
        f.write("%s hello.............\n"%(timecurrent))
def test1():
    print("this is test1")
    logger()
def test2():
    print("this is test2")
    logger()
def test3():
    print("this is test3")
    logger()

test1()
test2()
test3(

  函数的优点:

1.代码重用

2.一致性

3.可扩展性

def test1():
    print("in this is test1")

def test2():
    print("in this is test2")
    return 1
    print("return 以后")#只要先返回return 这行就不执行

def test3():
    print("in this is test3")
    return 0,"hello",["apple","banner"],{"name":"hunter"}
x=test1()
y=test2()
z=test3()

print(x)#返回none
print(y)#返回一个object
print(z)#返回一个元组

  

def test(x,y,z):
    print(x)
    print(y)
    print(z)

test(1,z=2,y=3)#如果有传递的参数既有位置参数又有关键参数,必须是位置参数优先。

 

def test(*args):#参数组 接受n个位置参数,转换成元组的形式
    print(args)#一个元组

test(1,2,3,4,5)
test(*[1,2,3,4,5,6])


def test1(x,*args):#位置参数,参数组
    print(x)
    print(args)

test1(1,2,3,4,5)

def test2(**kwargs):#kwargs 把n个关键字参数 转换成字典的形式
    print(kwargs)
test2(name="hunter",age=18,sex="man")
test2(**{'name':'hunter','age':20})

#位置参数不能写在关键参数后面

#大融合
def test3(name,age=18,*args,**kwargs):
    print(name)
    print(age)
    print(args)
    print(kwargs)

test3("hunter",27,1,2,3,4,sex='man')#位置参数,关键参数,

  注意:位置参数不能放在关键参数后面,*args是n个位置参数转换为元组,**kwargs是n个关键参数转换为字典。