在python中铃拇,定義一個函數(shù)要使用def語句钞瀑,依次寫出函數(shù)名、括號慷荔、括號中的參數(shù)和冒號:雕什,然后,在縮進(jìn)塊中編寫函數(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
擴(kuò)展名):
參數(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)常需要從一個點移動到另一個點惹资,給出坐標(biāo)贺纲、位移、角度褪测,就可算出新的坐標(biāo):
>>> 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ù):