Python notes(6)-自定义函数

Python 中用 def定义一个函数

def 函数名 (参数1,参数2,……):
    <语句>
    return

如果没有return语句,函数执行完毕后也会返回结果,只是结果为None。return None可以简写为return。

造轮子:

可以将自定义函数保存到py文件中 在该文件的当前目录下启动解释器 在开头用 from 文件名 import 函数名 导入自己的轮子

什么都不做的pass:

如果想在一个函数或者其他语句中(如if)什么都不做的话就可以用pass,否则代码将报错

自定义函数参数类型检测:

用isinstance()检测 >>>if not isinstance(x, (int, float)): … raise TypeError(‘bad operand type’) 抛出错误

多值返回:

Python允许函数return多个值

实际上Python函数返回的还是单一值(tuple)

而多个变量可以接受含有同样多元素的tuple的直接赋值,例:

import math
def move(x, y, step, angle=0):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny

>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0

>>> r = move(100, 100, 60, math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)