美文网首页
2018-07-28

2018-07-28

作者: 淡水t海边 | 来源:发表于2018-07-29 09:57 被阅读0次

函数的返回多个值:

import math  #导入math包,并允许后续代码引用math包中的sin,cos函数

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

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

r = move(100, 100, 60, math.pi / 6)

>>> print(r)

(151.96152422706632, 70.0)

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

相关文章

网友评论

      本文标题:2018-07-28

      本文链接:https://www.haomeiwen.com/subject/vxxomftx.html