天天看點

python學習筆記(三)函數

3.1函數的定義

def是定義函數的關鍵字,冒号表示接下來是函數體。
def CompareNum(a, b):
    if a > b:
        print(a, "is bigger than ", b)
    elif a == b:
        print(a, "is equal to", b)
    else:
        print(a, "is smaller than ", b)
        
CompareNum(2, 3);
           

運作結果:

2 is smaller than  3
           

3.2 global語句

global語句用來聲明變量是全局的,作用是在函數内使用定義在函數外的變量。
x = 20

def func():
    global x
    x = 2
    print("x is", x)

func()
print("x is", x) 
           

運作結果:

x is 2
x is 2
           

3.3非局部語句

非局部作用域位于局部作用域和全局作用域之間,下例中func()中定義的x即稱為非局部變量x。
def func():
    x = 20
    print("x is", x)
    def func_inside():
        nonlocal x
        x = 5
    func_inside()
    print("x is", x)

func()
           

運作結果:

x is 20
x is 5
           

3.4預設參數

預設參數是在函數定義的形參名後加上=和預設值。
def func(str, num = 1):
    print(str * num)

func("python")
func("python", 3)
           

運作結果:

python
pythonpythonpython
           

3.5關鍵參數

關鍵參數使用名字而不是位置來指定函數參數。優點是不必擔心參數的順序,以及在其他參數都有預設值時,隻給想要的參數指派。
def func(a, b = 1, c = 5):
    print("a is ", a, "b is ", b ,"c is ", c)

func(3, 4)
func(3, c = 10)
func(c = 10, a = 3)
           

運作結果:

a is  3 b is  4 c is  5
a is  3 b is  1 c is  10
a is  3 b is  1 c is  10
           

3.6 VarArgs參數

用*來定義一個任意個數參數的函數,用**來定義一個任意個數關鍵字參數的函數。
下例中*numbers表示參數被收集到number清單,**keywords表示關鍵字參數被收集到keywords字典。
def func(init = 5, *numbers, **keywords):
    count = init
    for i in numbers:
        count += i
    for key in keywords:
        count += keywords[key]
    return count


result = func(10, 1, 2, 3, veg = 1, fru = 2)
print("result = ", result)
           

運作結果:

result =  18
           

3.7 Keyword-only參數

帶星号的參數後面申明參數會導緻Keyword-only參數。如果參數沒有預設值,且不給它指派,如下例中func(10, 1, 2, 3)會引發錯誤。
def func(init = 5, *numbers, num):
    count = init
    for i in numbers:
        count += i
    count += num
    return count


result = func(10, 1, 2, 3, num = 2)
print("result = ", result)
           

運作結果:

result =  18
           

3.8 return語句

return語句用來從函數傳回。沒有return語句等價于return None。None表示沒有任何東西的特殊類型。如變量值為None,表示它沒有值。

3.9 DocStrings

DocStrings表示文檔字元串,它的作用是:使程式文檔簡單易讀。

文檔字元串位于函數的第一個邏輯行,一般是多行字元串,首行大寫字母開始,句号結尾。第二行是空行,第三行開始是詳細的描述,使用時盡量遵循上述慣例,__doc__用于擷取函數文檔字元串屬性。

def getMax(x, y):
'''Print the Maximum of two number.

   the num must be integers'''
x = int(x) #convert to integers
y = int(y)
if x > y:
	print(x, "is Maximum")
else:
	print(y, "is Maximum")

getMax(3, 5)
print(getMax.__doc__)
           

運作結果:

5 is Maximum
Print the Maximum of two number.
       the num must be integers