一、函数
#函数
def func1(): # def 定义函数 func1 函数名
"""testing"""
print('in the func1')
return 0
#过程(没有返回值的函数)
def func2(): # def 定义函数 funct1 函数名
"""testing"""
print('in the func2')
二、函数式编程
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\n'%time_current) #在末尾不断追加 写日志之类的功能
def test1():
print('in the test1') #初选函数,追加日志
logger()
# with open('a.text','ab') as f:
# f.write('end action\n')
def test2():
print('in the test2')
logger()
# with open('a.text', 'ab') as f:
# f.write('end action\n')
def test3():
print('in the test3')
logger()
# with open('a.text', 'ab') as f:
# f.write('end action\n')
test1() #引用
test2()
test3()
三、函数式编程之参数
def test1(): print('in the test1') return 0 #返回值后,下一行代码不运行 # print("test end") x = test1() print(x) def test1(): print('in the test1') def test2(): print('in the test2') return 0 def test3(): print('in the test3') return 1,'hello',['jack','wupeiqi'],{'name':'jack'} # 放在元组里返回 x=test1() y=test2() z=test3() print(x) print(y) print(z)
***总结:
- 返回值数=0,返回None
- 返回值数=1,返回obiect
- 返回值数>1,返回tuple
#返回值的作用:
因为想要函数有一个执行的结果,后面的程序(逻辑)要根据执行的结果进行操作。
#参数函数
#实参:实际存在的占用空间的 形参:x就像内存空间的表示,一个门牌号一样 def test(x,y): #x,y形参 1,2实参 (x,y)位置参数 print(x) print(y) test(1,2) #位置参数调用,与形参一一对应 test(y=2,x=1 ) #关键参数调用,与形参顺序无关 test(x=2,3) #不是纯粹的关键字调用,就按照位置参数调用(第一个x,第二个y) test(3,y=2) #关键参数不能放在位置参数前面
默认参数:
#默认参数 def test(x,y=2): print(x) print(y) test(1) #默认参数不赋值,就默认y=2 #默认参数的特点:调用函数的时候,默认参数非必须传递 #用途:1、默认安装值 2、默认值
参数组