天天看點

python傳回多個參數

傳回多個值

函數可以傳回多個值嗎?答案是肯定的。

比如在遊戲中經常需要從一個點移動到另一個點,給出坐标、位移和角度,就可以計算出新的新的坐标:

import math

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

import math

語句表示導入

math

包,并允許後續代碼引用

math

包裡的

sin

cos

等函數。

然後,我們就可以同時獲得傳回值:

>>> 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,但寫起來更友善。

再python的疊代文法中也可以看到這種傳回tuple的文法

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
...     print(key)
...
a
c
b