1.函数的定义 def 函数名():
def test():
print('hello')
2.函数的调用 函数名()
def test():
print('hello')
test()#此处调用函数
3.函数传参
(一)必传参数,也叫位置参数,函数调用的时候必须要传参数
a.全部用位置参数,位置一一对应传参
def test1(name,age):
print('name:%s,age:%s'%s(name,age))
test1('小青',500)
b.关键字传参,指定关键字不需要按照顺序来
def test2(name,age,phone):
print(name,age,phone)
test2(age=10,phone=110110,name='小白')
c.位置参数和关键字参数结合使用,要先用位置参数,再写关键字参数,关键字参数后不能用位置参数
def test3(name,age,phone,addr):
print(name,age,phone,aaddr)
test3('法海',23,addr='金山寺',phone=112112)
(二)默认值参数 函数调用的时候可以不传参数,不传参数的时候用默认的参数,传参数的时候用传的参数
def test1(name,age=18)#此处name是必传的形参,age是有默认值的形参
print('name:%s,age:%s'%(name,age))
#test1()#什么都不传调用函数会报错
test1('xiaohei')#输出为 name:xiaohei,age:18
test1('xiaobai',20)#输出结果为 name:xiaobai,age:20
(三)参数组
函数定义的时候参数组
def send_mail(*args):#加*,函数调用的时候不限制参数的个数类型
print(args)
send_mail()#输出结果为一个空元组()
send_mail('小黑')#输出结果为('小黑',)
send_mail('xiaohei','xioabiao','kaixin')#输出结果为('xiaohei','xioabiao','kaixin')
函数调用的时候(数组,元组)
def o_mysql(host,port,db,user,passwd):
print('连接成功')
data=('120.0.0.0',3306,'student','root','root')
o_mysql(*data)#解包,把列表拆成一个个元素对应传参
(四)关键字参数
函数定义里面关键参数
a.不必传
b.位置传参不可以
c.关键字传参可以
def test4(**info):
print(info)
test4()#打印一个空字典
test4('123')#此处会报错
test4(phone=110110)#{’phone‘:110110}
test4(name='xiaobai',age=18) #{‘name’:'xioabia','age':18}
函数调用的时候
def o_mysql(host,port,db,user,passwd):
print('连接成功')
data={'host':'120.0.0.0'
'port':3306
'db':'stu'
'user':'root'
'passwd':'123456'}
o_mysql(**data)#解包,把字典转换成host='120.0.0.0',port=3306,...关键字传参
4.匿名函数
a.使用lambda 定义没有函数名,lambda 参数列表:表达式
b.匿名函数的调用
b-1 :将创建好的匿名函数通过一个变量来接受
b-2:使用变量名调用匿名函数
f=lambda x,x2,x3:x+x2+x3
print(f(1,2,3)#输出结果为6