Python学习之路0x07
这一章我们来介绍Python的函数。
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。
Python定义函数的方法如下
def 函数名(参数表):
函数体
[return 返回值]
#下面让我们写几个测试函数
def sayHello():
print('Hello,world!')
def addFun(x,y):
return x+y;
def formatInfo(name,age):
print('Hello:{},{} years old is very buautiful age!'.format(name,age))
name = 'ekko'
age = 19
#调用函数时需要在函数名后加(),如果有参数列表需要传参数。
sayHello()
Hello,world!
print(addFun(10,17))
27
formatInfo(name,age)
Hello:ekko,18 years old is very beautiful age!
如果在参数前加*****,那么此变量会以元组的方式传入
def test(*pram):
for i in pram:
print(i)
test(1,2,3)
1
2
3
#这个小例子证明了传入参数是一个可迭代对象
当然还有加两个*****的情况,这会以字典的形式传入参数
def test2(**pram):
for i in pram:
print(i,pram[i])
test2(name='ekko',age=18,gender='male')
#输出如下
name ekko
age 18
gender male
最后我们介绍一下Python的匿名函数
#python的匿名函数使用lambda声明,形式->参数列表:需要返回的值
s = lambda x,y:x+y
print(s(1,3))