函数特性:减少重复代码,使程序变的可扩展,使程序变得易维护
1.定义函数
#定义函数 def func1(): """test""" print("this is test") return 0 #定义过程 #通俗的说过程就是没有返回的函数,但python会返回一个none def func2(): """test1""" print("this is test") #调用函数 x = func1() y = func2() #打印函数返回值 print(x,y) #0 None
2、函数返回值
#函数返回值作用:判断该函数执行情况。其他程序有可能需要根据该返回值进行不同的操作 def test1(): print("this is test") #返回none def test2(): print("this is test") return 0 #返回0 def test3(): print("this is test") return 1,"hello",["a","b"],{"a":"b"} #返回一个元组 x = test1() y = test2() z = test3() print(x) print(y) print(z)
3、函数参数
#1.位置参数和关键字参数 def test1(x,y,z): print(x) print(y) print(z) test1(1,2,3) #位置参数,与顺序有关 test1(y=2,z=3,x=1) #关键字参数,与位置无关 test1(1,z=3,y=2) #既有位置参数,又有关键字参数,位置参数不能再关键字参数前面 #2.默认参数 def test2(x,y=2): print(x) print(y) test2(1) #如果不指定y,则使用默认值,指定新值则用新值 test2(1,3) test2(1,y=3) #3.参数组 def test3(*args): #将传入值转化成一个元组 print(args) test3(1,2,3,4,5) test3(*[1,2,3,4,5]) #输出 # (1, 2, 3, 4, 5) # (1, 2, 3, 4, 5) def test4(x,*args): print(x) print(args) test4(1,2,3,4,5) #输出 # 1 # (2, 3, 4, 5) def test5(**kwargs): #将“关键字参数”转化成一个字典 print(kwargs) test5(y=1,x=2,z=3) #输出 # {'y': 1, 'x': 2, 'z': 3} def test6(name,age=18,**kwargs): print(name) print(age) print(kwargs) test6("feng",y=1,x=2) #输出 # feng # 18 # {'y': 1, 'x': 2} test6("feng",23,y=1,x=2) #输出 # feng # 23 # {'x': 2, 'y': 1}
4、局部变量与全局变量
name1 = "fengxiaoli" #全局变量,对所有函数生效,如果全局变量定义的是字符串或者数字,则在局部修改之后只对局部生效,\ def test(): #对全局还是没生效,如果全局变量定义的是字典,列表,集合,类,则在局部修改之后对全局也生效 #global name #在函数中声明全局变量,慎用 name1 = "cx" #局部变量,只在该函数中生效 print(name1) test() print(name1) # 输出: # cx # fengxiaoli name2 = ["cx","fengxiaoli"] def test2(): name2[0] = "CX" print(name2) test2() print(name2) # 输出: # ['CX', 'fengxiaoli'] # ['CX', 'fengxiaoli']
5、递归函数
#递归特性:必须有一个明确的结束条件。每次进入更深层次的递归,问题规模相比上次递归都应有所减少。递归效率不高 def calc(n): print(n) if int(n/2)>0: return (calc(int(n/2))) calc(10)
6、高阶函数
#变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数称为高阶函数 def test(a,b,f): res = f(a)+f(b) print(res) test(-5,3,abs) #这里的abs是一个求绝对值的函数
7、匿名函数
calc = lambda x:x*3 print(calc(3))