Python-函数

该系列转自:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/00137473843313062a8b0e7c19b40aa8f31bdc4db5f6498000

1、def my_abs(x):

  if x >= 0:

    return x

  else:

    return -x

2、定义空函数:

 def nop():

  pass

3、参数检查:

 如果参数个数不对,Python解释器会自动检查出来,但是如过参数类型不对,则无法帮助我们检查出来。

 数据类型检查可以使用内置函数instance实现:

def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x

 4、返回多个值:

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

但是这只是一个假象,Python函数返回的仍然是单一值:

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

返回值是一个tuple!

小结

定义函数时,需要确定函数名和参数个数;

如果有必要,可以先对参数的数据类型做检查;

函数体内部可以用return随时返回函数结果;

函数执行完毕也没有return语句时,自动return None

函数可以同时返回多个值,但其实就是一个tuple。


原文地址:https://www.cnblogs.com/jiangnanrain/p/4439435.html