函数就是将一大串重复的代码定义到一个容器中,调用这个容器实现此方法。好处就是减少代码的重复性,使程序可读性较强。
一:定义函数以及调用函数
>>> def test():
"这个是测试函数"
print("test")
>>> test.__doc__ #doc方法是查看函数的说明
'这个是测试函数'
>>> test() #调用函数
test
>>> a=test #将test函数的内存对象赋值给a,调用a就相当于调用test函数
>>> a()
test
二:有无返回值的函数
函数分为有返回值和无返回值的函数
============================================无返回值
>>> def test():
"这是一个没有返回值的函数"
print("test")
>>> a=test()
test
>>> print(a) #其实并不是没有返回值,只是返回一个None值
None
============================================有返回值
#函数的返回值可以是任何数据类型(布尔值,数字,字符串,列表,字典,元组等)
#返回单一的值
>>> def test():
return 1
>>> a=test()
>>> a
1
#返回多个值
>>> def test():
return 1,2,3,4
>>> a=test()
>>> a
(1, 2, 3, 4) #默认是元组的形式返回
#返回一个列表对象
>>> def test():
return [1,2,3,4]
>>> a=test()
>>> a
[1, 2, 3, 4]
#返回一个字典
>>> def test():
return {"name":"heitao","age":23}
>>> a=test()
>>> a
{'name': 'heitao', 'age': 23}
三:函数的参数
函数是可以代参数的,参数分为(位置参数,关键字参数,默认参数,参数组)
#位置参数(位置参数必须是一一对应的,形参和实参的数量必须相同)
>>> def test(a,b,c): #abc为形参,接收部分
print(a,b,c)
>>> test(1,2,3) #123为实参,传入部分
1 2 3
#关键字参数(关键字参数形参和实参数量要一致,同时如果位置参数和关键字参数必须混合使用时,位置参数必须在左边)
>>> def test(a,c,b):
print(a,b,c)
>>> test(1,2,b=3)
1 3 2
#默认参数(如果不传入参数默认是函数定义时的参数)
>>> def test(a,b,c=10):
print(a,b,c)
>>> test(1,2)
1 2 10
>>> test(1,2,c=50)
1 2 50
>>> test(1,2,3)
1 2 3
#参数组分为*args和**kwargs。其中kwargs为字典,args为列表
===============================args(可以接收0到任意多个参数,同时可以支持参数是一个列表)
>>> def test(*args):
print(args)
>>> test(1,2,3,4) #最终是元组的形式
(1, 2, 3, 4)
#传入一个列表
>>> def test(*args):
print(args)
>>> test([1,2,3,4])
([1, 2, 3, 4],)
>>> def test(*args):
for i in args:
print(i)
>>> test([1,2,3,4])
[1, 2, 3, 4]
#带*参数
>>> def test(*args):
print(args)
>>> test(*[1,2,3,4]) #会遍历整个列表
(1, 2, 3, 4)
#不带*参数
>>> def test(*args):
print(args)
>>> test([1,2,3,4]) #整体作为元组的一个元素
([1, 2, 3, 4],)
===============================kwargs(也可以接收多个值,是key=value的形式)
#不带*参数
>>> def test(**kwargs):
print(kwargs)
>>> test(name="heitao",Job="IT")
{'name': 'heitao', 'Job': 'IT'}
#带*参数
>>> def test(**kwargs):
print(kwargs)
>>> test(**{'name': 'heitao', 'Job': 'IT'})
{'name': 'heitao', 'Job': 'IT'}
#args和kwargs结合使用,args在左
>>> def test(*args,**kwargs):
print(args)
print(kwargs)
>>> test(*["heitao",23],**{"addr":"BJ","love":"woman"})
('heitao', 23)
{'addr': 'BJ', 'love': 'woman'}
注意:如果需要多种参数混合使用,位置如下:
位置参数——关键字参数——默认参数——args——kwargs
四:函数的全局变量VS局部变量
全局变量就是在整个程序中定义的变量,在任何子程序中都能调用的便是全局变量,而只有在某个子程序中定义的变量叫做局部变量。
===============================全局变量
>>> name="heitao" #此为全局变量
>>> def test(Name):
print(Name)
>>> def test1(NAME):
print(NAME)
>>> test(name) #可以调用
heitao
>>> test1(name) #可以调用
heitao
===============================局部变量
>>> def test():
name="这是test函数的name"
print(name)
>>> def test1():
print(name)
>>> test() #只有在test中生效
这是test函数的name
>>> test1() #test1中并没有定义name
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
test1()
File "<pyshell#106>", line 2, in test1
print(name)
NameError: name 'name' is not defined
===============================修改全局变量
#global用法
>>> info={"name":"heitao","addr":"BJ"}
>>> def test(**kwargs):
info["name"]="lisi"
print(kwargs)
>>> test(**info)
{'name': 'heitao', 'addr': 'BJ'}
>>> info
{'name': 'lisi', 'addr': 'BJ'}
>>> name="hello world"
>>> def test(Name):
global name
name="Hello World"
print(name)
>>> test(name)
Hello World
>>> name
Hello World
>>> name=[1,2,3,4]
>>> def test(*args):
name.append(6)
print(args)
>>> test(name)
([1, 2, 3, 4, 6],)
>>> name
[1, 2, 3, 4, 6]
#nonlocal用法(修改上一层)
>>> name="hello"
>>> def test():
name="Hello"
print(name)
def test1():
nonlocal name
name="HELLO"
print(name)
test1()
print(name)
>>> test()
Hello
HELLO
HELLO
>>> name
'hello'
五:递归函数
所谓递归函数就是自己调用自己,可以实现一个简单的死循环
#死循环
>>> def test():
print("hello world")
test()
>>> test()
#通过匿名函数来实现阶乘
#!/usr/bin/python3
#coding=utf8
#Author:HeiTao
num=int(input("输入一个数字,实现阶乘:"))
def test(num):
if num > 1:
return num *test(int(num-1))
else:
return num
sum=test(num)
print(sum)
#用递归函数来打印一个数除以2
#!/usr/bin/python3
#coding=utf8
#Author:HeiTao
num=int(input("输入一个数字,实现计算:"))
def test(num):
print(num)
if int(num/2) == 0:
return num
else:
return test(int(num/2))
print(test(num))
六:函数的作用域
所谓的函数的作用域就是将函数作为一个返回值,如下
>>> def test():
name="hello"
def test1():
print(name+"world")
return test1
>>> test() #这里test函数的返回值是一个test1函数的内存地址
<function test.<locals>.test1 at 0x0000000002DFF510>
>>> a=test()
>>> a() #这里实际调用的是test1函数
helloworld
>>> test()() #等同于a=test(),a()的结合体
helloworld
七:匿名函数
定义匿名函数是用lambda方法,如下
#定义的匿名函数
>>> a=lambda x,y:x+y #这里的x+y就相当于常规函数的return返回值
>>> a(1,2)
3
#匿名函数的作用
我们需要对一个列表进行从小到大排序时,我们可以这样做
>>> lst=[2312,1245,465,13,63342,3412]
>>> lst.sort()
>>> lst
[13, 465, 1245, 2312, 3412, 63342]
但是如果我们的列表的元素为字典,对字典的某个key进行可以用lambda函数,如下
>>> user=[{"name":"zhangsan","age":20},{"name":"azi","age":40},{"name":"lisi","age":12}]
>>> user.sort(key=lambda x:x['age'])
>>> user
[{'name': 'lisi', 'age': 12}, {'name': 'zhangsan', 'age': 20}, {'name': 'azi', 'age': 40}]
八:将匿名函数作为参数传给常规函数
>>> test=eval(input("输入一个匿名函数: "))
输入一个匿名函数: lambda x,y:x+y
>>> def test1(x,y,func):
return func(x,y)
>>> test1(1,2,test)
3