函数

比较重要的3种编程思路:

①:面向对象:华山派---》 类---》class

②:面向过程:少林派---》过程---》def

③:函数式编程:逍遥派---》函数---》def

本篇主要介绍第三个,函数式编程。

(一)过程和函数的区别:

定义一个过程:

def func2():
      print('in the func2 ')   过程就是没有返回值的函数而以,都可以被调用   

定义一个函数:

def func1():
      print('in the func1')   这一行代表逻辑,其实是这个函数想要干什么,可以是很多行
      return 0                    其实函数主要比过程多了这一行,多了一个返回值

x = func1()                      其实这一行意思是令x=函数的返回值
y = func2() 

print('from func1 return is %s' %x)
print('from func2 return is %s' %y)

最后的结果:

in the func1                           函数的逻辑
in the func2                           过程的逻辑
from func1 return is 0           因为这是一个函数他有返回值
from func2 return is None    无返回值

函数的一个应用:

import time
def logger():
      time_format = '%Y-%m-%d %X'                         从这一行开始往下的四行其实都是一个逻辑
      time_current = time.strftime(time_format)         将这一部分给定义为一个函数,以后方便调用
      with open('a.txt','a+') as f: 
             f.write('%s end action ' %time_current)  

def test1():                                                             这里面的每一个logger()都代表着上面的四
      print('in the test1')                                     行代码,如果没有定义函数,则会在引用的时候非
      logger()                                                     常的麻烦。
def test2():
      print('in the test2')
      logger()
def test3():
      print('in the test3')
      logger()

     return一个比较重要的作用时,我想知道这个代码的执行结果如何。 

原文地址:https://www.cnblogs.com/zaizaiaipython/p/7777857.html