1.编程的方法有三种:
面向对象:类:class
面向过程:过程:def 可以调用,无返回值
函数式编程:函数:def,可以调用,有返回值
函数的程序写法:
def test(x):
"The function definitions" #文档描述
x+=1 #代码块或程序处理逻辑
return #定义返回值
2.面向过程与函数式编程区别可以用有没有返回值来分辨,如以下代码:
#函数
def func1():
"testing"
print('in the func1')
return 0 #有返回值
#过程
def func2():
"testing2"
print('in the func2')
调用函数的时候直接写函数名即可:
x=func1() #调用函数
y=func2()
print(x)
print(y) #python中给过程定义了返回值None
可以看到函数与过程都可被调用,打印x,y,可以看到x的返回值为0,而y的返回值为None。
3.函数的优点,将代码重复利用;一致性;可扩展性;这里通过以下的例子来说明
我们需要对一个文档进行多次写入操作,那么可以将该写入操作写进一个函数中,调用即可,如以下:
(1)将操作写入一个函数中
def logger():
with open('a.txt','a+') as f:
f.write('end action %s\n')
(2)调用该函数
def test1():
print('test1 starting action...')
logger()
def test2():
print('test2 starting action...')
logger()
def test3():
print('test3 starting action...')
logger()
(3)执行test1,test2,test3
test1()
test2()
test3()
可以看到程序执行结果输出要打印的结果,在a.txt文档中追加三行end action
(4)如果要体现时间,可以在引入时间模块 import time,并且在logger函数中定义时间格式并打印。
time_format='%Y-%m-%d %X' #定义格式,年月日,X代表时分秒
time_current=time.strftime(time_format) #引用上面时间格式,按格式打印时间
with open('a.txt','a+') as f:
f.write('end action %s\n' %time_current)
那么在a.txt文档中就看到在写入的每行后面加入了时间