文章目录
1、函数的定义
函数:为了提高编写的效率以及代码的复用性,所以把具有独立功能的代码块组织为一个小模块,这些小模块就是函数。
定义函数的格式如下:
def (函数名):
代码块
def test():
print("test")
2、函数的调用
要想实现函数的功能,需要调用函数,通过使用"函数名()"即可完成调用。
注意:每次调用函数时,函数都会重新开始执行,当这个函数中的代码执行完毕之后,意味着调用就结束了。如果函数执行过程中遇到return,也会结束。
In [1]: def test():
...: print("test")
In [2]: test()
test
3、函数的文档说明
help(func) ,直接查看函数的使用说明
func.doc,直接查看函数的文档说明
In [3]: help(print) # 可查看内置函数的使用说明
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
In [4]: print.__doc__ # 可查看内置函数的文档说明
Out[4]: "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
4、函数的参数
4.1 位置参数
位置参数必须以正确的位置顺序传入函数,调用时的数量必须和声明时的一样,不然会报错。
In [5]: def add(x, y):
...: print(x)
...: print(y)
...: return x + y
In [6]: add(1, 2)
1
2
Out[6]: 3
4.2 默认参数
调用有参数的函数时,如果没有传递参数,则会使用默认参数,默认参数可以简化函数的调用。
设置默认参数时,需要注意的是:
- 存在位置参数时,位置参数在前,默认参数在后,否则会报错。
- 当函数有多个参数时,把变化大的参数放在前面