python---函数,,函数学习,要点总结如


函数学习,要点总结如下:

1. 函数默认可以没有返回值,没有返回值则返回为None
2. 函数可以有多个返回值,类型可以不同,但其实多个返回值整体上是一个元组
3. 关键参数不能够写在位置参数前面
 1 # -*- coding:utf-8 -*- 2 # LC 3  4 import time 5 #函数: 6 def logger():               #定义日志函数 7     time_format = ‘%Y-%m-%d  %X‘        #定义时间格式 8     time_current = time.strftime(time_format)       #抓取当前时间 9     with open("log_file","a") as f:10         f.write("%s this is end\n"%time_current)11 12 def func1():13     """to declare the function"""           #说明这个函数是做什么的14     print("this is function1")              #函数工作模块,逻辑15     logger()16     return 0                                    #函数返回值17 18 #过程:                #过程是没有返回值的函数,在python中,过程默认返回None19 def func2():20     """function 2"""21     print("this is function2")22     logger()23     return 1,{"name":"lvcheng","age":"18"}      #可返回多个值24 25 x = func1()             #调用函数26 y = func2()27 print(x)28 print(y)29 30 def func3(x,y,z):              #x,y为形参,同为位置参数31     print(x,y,z)32     return x,y,z33 34 func3(1,2,3)          #位置参数调用,位置需要与形参一一对应35 func3(1,2,z=3)36 func3(y=2,z=3,x=1)      #关键字调用,关键参数,与形参顺序无关37 38 #默认参数39 def func4(x,y=3):        #y是默认参数40     print(x)41     print(y)42 func4(1)43 func4(1,5)44 #默认参数可以不传递,如果有传递,则是传递的值45 #用途 1,默认安装的时候,2, 链接数据库的端口号等46 47 #参数组,对于实参不固定函数的实现48 def func5(*args):       # *是关键字,元组的方式传递49     print(args)50 51 # *args接受N个位置参数,转换成元组的方式52 53 test1 = func5(1,2,3,4,5)    # 1,2,3,4,5以(1,2,3,4,5)元组的方式传递给args54 test1 = func5(*[1,2,3,4])55 56 #参数组,以字典的方式实现57 58 def func6(**kwargs):59     print(kwargs)60     print(kwargs[‘name‘])       #取字典里的值61     print(kwargs[‘age‘])62 # **kwargs接收N个关键字参数,转换成字典的方式传递63 64 65 test2 = func6(name="lc",age=9)          #必须传递关键字参数66 test2 = func6(**{"name":"lc","age":10})67 68 69 def func7(name,age=19,**kwargs):        #有形参,有默认参数,有参数组70     print(name)71     print(age)72     print(kwargs)73 74 test3 = func7("lc",21,sex="M",hobby="girl")75 test3 = func7("lc",sex="M",hobby="girl",age = 32)76 77 def func8(name,age=19,*args,**kwargs):78     print(name)79     print(age)80     print(args)81     print(kwargs)82 83 func8("lc",2,3,4,sex="M",hobby="money")

python---函数

评论关闭