在python中,定義一個函數(shù)要使用def語句,依次寫出函數(shù)名、括號、括號中的參數(shù)和冒號:,然后,在縮進塊中編寫函數(shù)體,函數(shù)的返回值用return語句返回。
首先自定義一個求絕對值的zl_abs函數(shù)為例:
def zl_abs(x):
if x >= 0:
return x
else:
return -x
為了避免混淆,我們接下來定義Drzl函數(shù)。
如果你已經(jīng)把Drzl_abs()的函數(shù)定義保存為abstext.py文件了,那可以在該文件的當(dāng)前目錄下啟動Python解釋器,用from abstext import Drzl_abs來導(dǎo)入Drzl_abs()函數(shù),注意abstest是文件名(不含.py擴展名):
參數(shù)檢查
調(diào)用函數(shù)時,如果參數(shù)個數(shù)不對,python解釋器會自動檢查出來,并拋出異常TypeError
Drzl_abs(-87,909)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Drzl_abs() takes 1 positional argument but 2 were given
但是如果傳入的參數(shù)類型不對,Python解釋器就無法幫我們檢查。試試Drzl_abs和內(nèi)置函數(shù)```abs``的差別:
Drzl_abs("f")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "F:\pyFile\abstext.py", line 3, in Drzl_abs
raise TypeError('bad operand type')
TypeError: unorderable types: str() >= int()
abs('f')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
讓我們改一下 Drzl_abs的定義,對參數(shù)類型做檢查,只允許整數(shù)和浮點數(shù)類型的參數(shù)。數(shù)據(jù)類型檢查可以使用內(nèi)置函數(shù)isinstance()實現(xiàn):
def Drzl_abs(x):
if not isinstance(x,(int, float)):
raise TypeError('bad operand type')
if x > 0:
return x
else:
return -x
添加參數(shù)檢查后,如果傳入錯誤的參數(shù)類型,函數(shù)就可以拋出一個錯誤:
Drzl_abs("f")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "F:\pyFile\abstext.py", line 3, in Drzl_abs
raise TypeError('bad operand type')
TypeError: bad operand type
返回多個值
函數(shù)可以返回多個值嗎?答案是肯定的。
比如在游戲中經(jīng)常需要從一個點移動到另一個點,給出坐標、位移、角度,就可算出新的坐標:
>>> 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語句表示導(dǎo)入 math包,并允許后續(xù)代碼引用math包里的sin、cos等函數(shù)。然后我們就可以同時獲得返回值:
>>> x,y = move(100,100,60,math.pi / 6)
>>> print(x,y)
151.96152422706632 70.0
但其實著只是一種假象,Python函數(shù)返回的仍然時單一值:
>>> def move(x,y,step,angle=0):
... nx = x + step *math.cos(angle)
... ny = y - step * math.sin(angle)
... return nx,ny
...
>>> r = move(100,100,60,math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)
>>>
原來返回值是一個tuple!但是,在語法上,返回一個tuple可以省略括號,而多個變量可以同時接收一個tuple,按位置賦給對應(yīng)的值,所以,Python的函數(shù)返回值其實就是返回一個tuple,但寫起來更方便。
小結(jié):
定義函數(shù)時,需要確定函數(shù)名和參數(shù)個數(shù);
如果有必要,可以先對參數(shù)的數(shù)據(jù)類型做檢查;
函數(shù)體內(nèi)部可以用return隨時返回函數(shù)結(jié)果;
函數(shù)執(zhí)行完畢也沒有return語句是,自動return None。
函數(shù)可以同時返回多個值,但其實就是一個tuple。
練習(xí)
請定義一個函數(shù)quadratic(a,b,c),接收3個參數(shù),返回一元二次方程:
ax^2 + bx + c = 0的兩個解。
提示:計算平方根可以調(diào)用math.sqrt()函數(shù):