函数的构成
当我们在编程过程中,发现某些功能可能会一直在我们的整个程序中使用,那么这里就需要函数来实现对功能的包装
def语句
def语句可以在运行时,创建一个新的函数对象并赋值给一个变量名
def语句可以出现在一个Python脚本任何地方
def语句定义函数可以嵌套,甚至是在if语句中
>>> def func():
... print('hello world')
...
>>> func()
hello world
参数
参数是我们在定义一个函数时,可能需要在函数内部处理一些外界的变量,那么需要通过参数来进行数据的导入
>>> def func(a,b):
... return a + b
...
>>> var = func(1,2)
>>> var
3
- 形参: 定义函数时后面括号里所写的形式参数,如这里的a, b,也称形参
- 可理解为占位意义
- 实参: 在函数实际调用时,如这里的1, 2传入的数据为实参,也称实际参数
必备参数
定义函数时的形参,在我们传递实参时,需要数量和顺序保持一致
>>> def func(age,sex):
... print('bob age is %d, sex is %s ' % (age, sex))
...
>>> func(10,'male') #按照规矩来
bob age is 10, sex is male
>>> func('男性',20) #不按规矩来,第一个位置的值被填写到了print时的%d处,引发错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func
TypeError: %d format: a number is required, not str
>>> func(10) #少传了一个参数,也会引发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() missing 1 required positional argument: 'sex'
命名参数
我们可以通过命名传参的方式,打乱传递参数的顺序
>>> def func(age,sex):
... print('bob age is %d, sex is %s ' % (age, sex))
...
>>> func(sex='女人',age=18)
bob's age is 18, sex is 女人
缺省参数
某些情况下,可能我们的函数会经常处理一些相同的数据,那么可以通过在形参中定义缺省参数的方式来实现
缺省参数一定是从右向左的顺序来设置
因为实参默认的接收顺序为从左向右,如果缺省参数之后还有一个需要传递值的形参,那么可能因为缺省参数已经被覆盖了值,而导致后面位置的形参无法接收到实际值而报错
>>> def func(today,wea='Sunny'):
... print('today is %s, weather is %s.' % (today,wea))
...
>>> func('礼拜一')
today is 礼拜一, weather is Sunny.
不定长参数
某些时候我们需要传入的实参可能无法在形参处确定,那么可以使用不定长传参的方式
*args:接收不定长参数为元组形式
>>> def func(*arg):
... print(type(arg))
... print(arg)
...
>>> func(1,2,3,4,5) #传入不定长实参
<class 'tuple'> # *arg接收不定长实参会被保存为元组类型
(1, 2, 3, 4, 5)
**kwargs:接收不定长参数为键值对形式(字典)
>>> def func(**arg):
... print(type(arg))
... print(arg)
...
>>> func(a=1,b=2,c=3)
<class 'dict'> # **arg 接收不定长键值对形式实参会被保存为字典类型
{'a': 1, 'b': 2, 'c': 3}
>>> func(1,2,3) # **arg 格式接收不是键值对形式的参数,将会爆出TypeError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes 0 positional arguments but 3 were given
返回值
- return语句:
- 可以返回任意类型的对象作为返回值(包括函数,对象实例等)
- 同时也可以返回多个值,在返回多个值时,会处理为一个元组
- 返回的值可以通过函数调用之后使用等号(=)赋值给一个变量
>>> def func():
... return 1,2
...
>>> var = func()
>>> var
(1, 2)