首先函数是什么呢????函数封装了一个功能,需要的时候就去调用就好,def ret_demo(dic):#1.先定义一个函数 while True:#3.开始执行while循环 if len(dic) > 3:#4.判断长度是否大于三, print("长度超了") return False#5.返回一个 False,return是结束标志 break #return后面的不执行 else: print(‘长度刚刚好‘) ret = ret_demo([1,2,3,4,5])#2.函数的调用,传入参数print(ret)#最后输出def ret_demo1(): return 1,2,3,4#输出(1,2,3,4)def ret_demo2(): return 1 #只返回1def ret_demo3(): return 1,#返回元组的形式(1,)def ret_demo4(): return (1,2,3)#返回(1,2,3)def ret_demo5(): return (1,2,3),4#((1,2,3)4)def ret_demo6(): return ‘a‘,‘b‘,‘c‘,56 #(‘a‘,‘b‘,‘c‘,56 )def ret_demo7(): return (1,2,3),(1,2),[33,44],{‘name‘:‘jx‘,‘age‘:12}#( (1,2,3),(1,2),[33,44],{‘name‘:‘jx‘,‘age‘:12})def ret_demo8(): return {1,2,3} #竟然返回的是字典def ret_demo9(): return [1,2,3]#返回的是列表print(ret_demo1())print(ret_demo2())print(ret_demo3())print(ret_demo4())print(ret_demo5())print(ret_demo6())print(ret_demo7())print(ret_demo8())print(ret_demo9())def trans_para(a,b): print(a,b)trans_para(20,30,2)#这是错误的,按位置传参,那个2没有参数来接收 b,关键字传参。def trans_para(a,b): print(a,b)trans_para(b=30,a=20)#按关键字传参,位置前后不重要 c,混合参数(位置参数必须在前面) def trans_para(a,b,c): print(a,b,c)trans_para(10,20,c=40) d,默认参数。def trans_para(a,b,c="a"): print(a,b,c)trans_para(10,20,c=40) 10,20,40trans_para(10,20)#10,20,a e,不定长参数*args,**kwargs。def trans_para(*args,**kwargs): print(args,type(args)) print(kwargs,type(kwargs))trans_para("jinxin",12,[1,2,3,4],[3,4,],(1,4,7),{"a":"123","c":456},country="china")#"jinxin",12,[1,2,3,4],[3,4,],(1,4,7),{"a":"123","c":456}#country="china"def foo(*args,**kwagrs): print(‘args=‘,args) print(‘kwargs=‘,kwagrs) print(‘------------------‘)if __name__==‘__main__‘:#用来做输出的 foo(1,2,3,4) foo(a=1,b=2,c=3) foo(1,2,3,4,a=1,b=2,c=3) foo(‘a‘,1,None,a=1,b=‘2‘,c=3)#*kwargs用来接收关键字传参其余类型都由*args接收*args和**kwargs是python中的可变参数,*args表示任何多个无名参数,他是一个tuple**kwargs表示关键字参数,他是一个dict.并且同时使用*args和**kwargs时,必须*args参数列要在**kwargs前,像foo(a=1,b=2,c=3,a,1,None)这样调用的话,会提示语法错误 创建字典def kw_dict(**kwargs): return kwargsprint(kw_dict(a=1,b=2,c=3)=={‘a‘:1,‘b‘:2,‘c‘:3})dict(a=1,b=2,c=3)print(dict)def extendList(val,list=[]): list.append(val) return listlist1 = extendList(10,)print(‘list1=%s‘%list1)#[10,] list2 = extendList(123,[])#[123]print(‘list2=%s‘%list2) list3 = extendList(‘a‘)print(‘list3=%s‘%list3)#[10,‘a‘] def extendList(val,list=[]): list.append(val) return listlist1 = extendList(10,)list2 = extendList(123,[])list3 = extendList(‘a‘) print(‘list1=%s‘%list1) #[10,‘a‘]print(‘list2=%s‘%list2) #[123]print(‘list3=%s‘%list3) #[10,‘a‘]
时间: 2024-10-19 11:05:46