Python--函数&过程,


函数式编程与过程式编程打的区分:过程是没有返回值的函数,过程在python3中也有返回值,为None

函数的作用:代码复用、保持代码的一致性、使代码更容易扩展

过程的定义与调用:

1 def func2():
2     """testing2""" # 过程的描述
3     print("in the func2")
4 y=func2()
5 print(y)
6 # >>> in the func2
7 # >>> None

函数的定义与调用:

1 def func1():
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 def func1():
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 def func():
 2     print("I`m  func")
 3     return 0
 4 
 5 def func1():
 6     """testing1""" # 函数的描述
 7     print("in the func1")
 8     return func
 9 x=func1()
10 print(x)
11 # >>> in the func1
12 # >>> <function func at 0x00000223A2ADC040>

模拟程序调用日志函数,打印日志到文件(带时间):

 1 import  time
 2 def logger():
 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     return 0
 9 
10 def test1():
11     print('in the test1')
12     logger()
13     return 0
14 
15 def test2():
16     print('in the test2')
17     logger()
18     return 0
19 
20 test1()
21 test2()

相关内容

    暂无相关文章

评论关闭