Python学习杂记七

来源:互联网 发布:深圳青年旅社知乎 编辑:程序博客网 时间:2024/06/05 12:02
def my_abs(x):    if not isinstance(x, (int, float)):        raise TypeError('bad operand type')    if x >= 0:        return x    else:        return -x

函数可以返回多个值吗?答案是肯定的。

比如在游戏中经常需要从一个点移动到另一个点,给出坐标、位移和角度,就可以计算出新的新的坐标:

import mathdef 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, y151.961524227 70.0

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

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

原来返回值是一个tuple!但是,在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值,所以,Python的函数返回多值其实就是返回一个tuple,但写起来更方便。


def power(x, n):    s = 1    while n > 0:        n = n - 1        s = s * x    return s


0 0
原创粉丝点击