python--10 函数
为了使程序代码更为简单,我们需要把程序分为越来越小的部分
对象 函数 模块
创建函数
>>> def myFirstFunction():
... print('这是我创建的第一个函数')
... print('感觉不错,继续继续')
...
>>> myFirstFunction()
这是我创建的第一个函数
感觉不错,继续继续
>>> mySecondFunction()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mySecondFunction' is not defined
代参数的函数
>>> def mySecondFunction(name):
... print(name + ',I LOVE YOU')
...
>>> mySecondFunction()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: mySecondFunction() missing 1 required positional argument: 'name'
>>> mySecondFunction('JUNJIE')
JUNJIE,I LOVE YOU
多个参数的函数 --对参数的个数没有限制
>>> def add(num1, num2):
... result = num1 + num2
... print(result)
...
>>> add(1,3)
4
有返回值的函数 return
>>> def add(num1, num2):
... return num1 + num2
...
>>> print(add(1,5))
6
形式参数 实际参数
函数调用过程中的参数是形参
传递进方法来的参数叫实参
函数文档
>>> def myfirstFunction(name):
... '函数定义过程中的Name是形参'
... #因为Ta只是一个形式,表示占据一个参数位置
... print('传递进来的' + name + '是实参,因为Ta是具体的参数值')
...
>>> myfirstFunction('俊杰')
传递进来的俊杰是实参,因为Ta是具体的参数值
>>> myfirstFunction.__doc__ __doc__默认属性
'函数定义过程中的Name是形参'
>>>help(myfirstFunction)
Help on function myfirstFunction in module __main__:
myfirstFunction(name)
函数定义过程中的Name是形参
关键字参数
>>> def SaySome(name, words):
... print(name + "->" + words)
...
>>> SaySome('junjie','everything is ...')
junjie->everything is ...
>>> SaySome(name = 'junjie', words = 'everything is ...')
junjie->everything is ...
默认参数 定义了默认值的参数
>>> def SaySome(name = 'junjie', words = 'ebable'):
... print(name + '->' + words)
...
>>> SaySome
<function SaySome at 0x7f5f445d7bf8>
>>> SaySome()
junjie->ebable
>>> SaySome('dog', 'animal')
dog->animal
收集参数/可变参数 参数前面加上* 收集参数用元组进行打包
>>> def test(*params):
... print('参数类型是:' , type(params))
... print('第二个参数是:' , params[1])
... print('参数的长度是:' , len(params))
...
>>> test(1,2,3,4,5,6)
参数类型是: <class 'tuple'>
第二个参数是: 2
参数的长度是: 6
可变参数 + 参数
>>> def test(*params, exp):
... print('参数的长度是:' , len(params), exp)
... print('参数类型是:' , type(params))
... print('第二个参数是:' , params[1])
...
>>> test(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() missing 1 required keyword-only argument: 'exp'
>>> test(1, 2, 3, 4, 5, 6, exp = 8)
参数的长度是: 6 8
参数类型是: <class 'tuple'>
第二个参数是: 2
>>> def test(*params, exp = '默认值'):
... print('参数的长度是:' , len(params), exp)
... print('参数类型是:' , type(params))
... print('第二个参数是:' , params[1])
...