函數能夠返回多個值嗎?答案是確定的。ide
好比在遊戲中常常須要從一個點移動到另外一個點,給出座標、位移和角度,就能夠計算出新的座標:函數
# math包提供了sin()和 cos()函數,咱們先用import引用它:spa
import math
def move(x, y, step, angle):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
這樣咱們就能夠同時得到返回值:code
>>> x, y = move(100, 100, 60, math.pi / 6) >>> print x, y 151.961524227 70.0
但其實這只是一種假象,Python函數返回的仍然是單一值:遊戲
>>> r = move(100, 100, 60, math.pi / 6) >>> print r (151.96152422706632, 70.0)
用print打印返回結果,原來返回值是一個tuple!ip
可是,在語法上,返回一個tuple能夠省略括號,而多個變量能夠同時接收一個tuple,按位置賦給對應的值,因此,Python的函數返回多值其實就是返回一個tuple,但寫起來更方便。it
一元二次方程的定義是:ax² + bx + c = 0io
請編寫一個函數,返回一元二次方程的兩個解。class
注意:Python的math包提供了sqrt()函數用於計算平方根。import
請參考求根公式:x = (-b±√(b²-4ac)) / 2a
參考代碼:
import math def quadratic_equation(a, b, c): t = math.sqrt(b * b - 4 * a * c) return (-b + t) / (2 * a),( -b - t )/ (2 * a) print quadratic_equation(2, 3, 0) print quadratic_equation(1, -6, 5)