從零開始學Python-Day15-定義函數

def

定義一個函數,要使用def語句,依次寫出函數名、括號、括號中寫參數、括號、冒號,然後,在縮進塊中編寫函數體,也就是計算過程,函數的返回值用return語句返回。我們可以自己定義一個取絕對值的函數my_abs

<code>>>> def my_abs(x):
\tif x>=0:
\t\treturn x
\telse:
\t\treturn -x

>>> my_abs(-2)
2/<code>

在函數體的內部,一旦符合條件執行了return,整個函數體運行就結束了。也就是之前說過的條件判斷,一旦符合條件就執行對應的語句結束。如果沒有return語句,函數體執行結束也要返回結果,結果為None;retuen None可以直接寫為retuen,如下兩個函數定義,如果傳入參數為0時,我們讓它返回None,運行的結果都是None

<code># -*- coding: UTF-8 -*-
# Filename : newf.py
# author by : www.woodmanzhang.com
# 新的函數
def my_function(x):
\tif x>0:
\t\treturn x
\tif x<0: return -x print(my_function(0)) def my_function2(x): if x>0:
\t\treturn x
\tif x<0:
\t\treturn -x
\telse:
\t\treturn
print(my_function2(0))/<code>

我們在存放了newf.py文件的目錄下啟動python3交互模式,就可以直接調用這個函數my_function:

<code>>>> from newf import my_function
None
None
>>> my_function(100)
100
>>> my_function2(100)

Traceback (most recent call last):
File "", line 1, in
NameError: name 'my_function2' is not defined
>>> from newf import my_function2
>>> my_function2(100)
100/<code>

注意,只有在當前環境調用了的函數才能使用,你可以將自己定義的函數存放在一個文件中,供自己使用調用。調用的方式為 from 文件名 import 函數名

空函數

空函數即為什麼都不做,用pass語句完成,跟打牌的pass一個意思,這段我還沒想好咋寫,先pass,讓程序可以運行起來,如果沒有pass就會有語法錯誤,還是上面的例子,我只要非零證書,零我不要,負數我還沒想好,修改如下:

<code>def my_function3(x):
\tif x>0:
\t\treturn x
\tif x<0:
\t\tpass
\telse:
\t\treturn/<code>

參數檢查

調用函數時,如果參數個數不對,Python解釋器會自動檢查出來,並給出TypeError如果參數類型不對,自定義函數和內置函數就有區別了,我們的自定義函數是在執行過程中報錯,說明了不能在數值和字符串之間進行’>=’的運算;而內置函數直接告訴我們不可以使用字符串:

<code>>>> my_abs(1,2)
Traceback (most recent call last):
File "<pyshell>", line 1, in
my_abs(1,2)
TypeError: my_abs() takes 1 positional argument but 2 were given
>>> my_abs('A')
Traceback (most recent call last):
File "<pyshell>", line 1, in
my_abs('A')
File "<pyshell>", line 2, in my_abs
if x>=0:
TypeError: '>=' not supported between instances of 'str' and 'int'
>>> abs('A')
Traceback (most recent call last):
File "<pyshell>", line 1, in
abs('A')
TypeError: bad operand type for abs(): 'str'/<pyshell>/<pyshell>/<pyshell>/<pyshell>/<code>

我們修改一下my_abs的定義,增加一個參數類型檢查,這裡只允許整數和浮點數參數傳入,參數檢查用內置函數isinstance(),報錯信息就會直接顯示出來:

<code>>>> def my_abs(x):
\tif not isinstance(x,(int,float)):
\t\traise TypeError('bad operand type')
\tif x>=0:
\t\treturn x
\telse:
\t\treturn -x

>>> my_abs('A')
Traceback (most recent call last):
File "<pyshell>", line 1, in
my_abs('A')
File "<pyshell>", line 3, in my_abs
raise TypeError('bad operand type')
TypeError: bad operand type/<pyshell>/<pyshell>/<code>

這裡其實就是在函數的定義的函數體前面增加了最初的條件判斷,為我們進行參數類型檢查。

用tuple返回多個值

一個函數如何返回多個值?我們都知道一元二次方程有兩個根,那該如何求解呢?

一元二次方程的求根公式為:

從零開始學Python-Day15-定義函數

計算平方根可以調用math.sqrt()函數

<code>import math
def f2(a,b,c):
\tif not (isinstance(a, (int,float)) and isinstance(b, (int,float)) and isinstance(c, (int,float))):
\t\traise TypeError('bad operand type')
\ty=b**2-4*a*c
\tif a==0:
\t\tif b==0:
\t\t\tprint('無解')
\t\tif b!=0:
\t\t\tx1=-c/b
\t\t\tprint('x=',x1)
\telse:
\t\tif y==0:
\t\t\tx1=-b/(2*a)
\t\t\tprint('x=',x1)
\t\tif y<0:
\t\t\tprint('無解')
\t\telse:
\t\t\tx1=(-b+math.sqrt(y))/(2*a)
\t\t\tx2=(-b-math.sqrt(y))/(2*a)
\t\t\tprint('x1=',x1,'\\n''x2=',x2)/<code>

import導入math函數包,我們定義move為運動後x,y軸數據計算的函數。原來返回值是一個tuple!但是,在語法上,返回一個tuple可以省略括號,而多個變量可以同時接收一個tuple,按位置賦給對應的值,所以,Python的函數返回多值其實就是返回一個tuple,但寫起來更方便。


分享到:


相關文章: