函数式编程与过程式编程打的区分:过程是没有返回值的函数,过程在python3中也有返回值,为None
函数的作用:代码复用、保持代码的一致性、使代码更容易扩展
过程的定义与调用:
1 deffunc2():
2 """testing2""" # 过程的描述
3 print("in the func2")
4 y=func2()
5 print(y)
6 # >>> in the func2
7 # >>> None
函数的定义与调用:
1 deffunc1():2 """testing1""" #函数的描述
3 print("in the func1")4 return 0 #结束函数、返回可被变量接收的值
5 print("你猜会不会打印我")6 x=func1()7 print(x)8 #>>> in the func1
9 #>>> 0
函数返回值可以为多个值,且值的数据类型可以有多种
1 deffunc1():2 """testing1""" #函数的描述
3 print("in the func1")4 return 1, ["a", "b"], {"name": "abc"}, "hello"
5 x=func1()6 print(x)7 #>>> in the func1
8 #>>> (1, ['a', 'b'], {'name': 'abc'}, 'hello') #元组
函数返回值为另一个函数时,返回另一个函数的内存地址
1 deffunc():2 print("I`m func")3 return04
5 deffunc1():6 """testing1""" #函数的描述
7 print("in the func1")8 returnfunc9 x=func1()10 print(x)11 #>>> in the func1
12 #>>>
模拟程序调用日志函数,打印日志到文件(带时间):
1 importtime2 deflogger():3 time_format = '%Y-%m-%d %X' #定义输出的时间格式
4 #strftime() 函数接收以时间元组,并返回以可读字符串表示的当地时间,以定义的时间格式输出时间
5 time_current =time.strftime(time_format)6 with open('a.txt', 'a+') as f:7 f.write('%s end action\n' %time_current)8 return09
10 deftest1():11 print('in the test1')12 logger()13 return014
15 deftest2():16 print('in the test2')17 logger()18 return019
20 test1()21 test2()