#函数定义 def mylen(): """计算s1的长度""" s1 = "hello world" length = 0 for i in s1: length = length+1 print(length) #函数调用 mylen() ''' ''' def mymax(x,y): the_max = x if x > y else y #if语句还可以这么写,长知识了 return the_max m1 = mymax(10,20) #按位置传递参数 m2 = mymax(x=5,y=10) #按形参名传递参数 m3 = mymax(5,y=6) #混合使用 print(m1) #20 print(m2) #10 print(m3) #6 ''' ''' def stu_info(name,sex = "male"): #默认参数 """打印学生信息函数,由于班中大部分学生都是男生, 所以设置默认参数sex的默认值为'male' """ print(name,sex) stu_info('alex') stu_info('eva','female') ''' ''' def defult_param(a,l = []): #默认参数是个可变类型 l.append(a) print(l) #l.pop() #可以通过pop使l变回空列表,这样就避免了可变默认参数的陷阱 defult_param('alex') #['alex'] #这样出现了错误,l=[]形参是可变类型,在第一次调用的时候值就改变了 defult_param('egon') #['alex', 'egon'] 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}) <class 'tuple'> #{'country': 'china'} <class 'dict'> #动态参数,也叫不定长传参,就是你需要传给函数的参数很多,不定个数,那这种情况下,你就用*args,**kwargs接收,args是元祖形式,接收除去键值对以外的所有参数,kwargs接收的只是键值对的参数,并保存在字典中。*args和 **kwargs
def function(arg,*args,**kwargs): #这是比较全的形参数 print(arg,type(arg)) #arg只能接收一个变量 print(args,type(args)) #args可以接收除键值对的所有变量并存在元组中 print(kwargs,type(kwargs)) #kwargs可以接收键值对,保存在字典中 function("jinxin",12,[1,2,3,4],[3,4,],(1,4,7),{"a":"123","c":456},country="china") # jinxin <class 'str'> # (12, [1, 2, 3, 4], [3, 4], (1, 4, 7), {'a': '123', 'c': 456}) <class 'tuple'> # {'country': 'china'} <class 'dict'>