1. 程式人生 > >筆記-python-tutorial-4.controlflow( and function)

筆記-python-tutorial-4.controlflow( and function)

-- 解包 案例 一個數 name incr 字符串 file through

筆記-python-tutorial-4.controlflow( and function)

1. 函數

1.1. 定義函數

def name(x):

“””函數的第一行語句可以是可選的字符串文本,即函數的文檔字符串,或docstring”””

if x>= 0:

return x

空函數

def nop():

pass

函數引用的實際參數在函數調用時引入局部符號表,實參總是傳值調用

函數可返回多個值,但實際返回的是一個tuple

2、 默認參數值

def ask_ok(promt,retries=4,complaint=’yes or no.’)

3、 引用

如果函數保存到.py文件中,使用

from file_name import func_name()

來導入函數,註意文件名不包括.py

2. 函數相關

2.1. 函數參數

1.位置參數

2.default argument values:

def ask_ok(prompt, retries = 4, reminder=’Please try again!’):

註意:默認參數的值僅在編譯時確認一次,此後不在修改

i = 5

def f(arg=i):

print(arg)

i = 6

f() #print 5

這在默認參數引用空表時會導致結果異常

def f(a, L=[]):

L.append(a)

return L

print(f(1))

print(f(2))

print(f(3))

This will print

[1]

[1, 2]

[1, 2, 3]

解決辦法是

def f(a, L=None):

if L is None:

L = []

L.append(a)

return L

3.keyword argument:

def parrot(voltage, state=‘a stiff‘, action=‘voom‘, type=‘Norwegian Blue‘):

註意關鍵字參數必需跟在位置參數後面;

4.可變參數: *argv

定義可變參數和定義一個list或tuple參數相比,僅僅在參數前面加了一個*號。在函數內部,參數numbers接收到的是一個tuple,因此,函數代碼完全不變。但是,調用該函數時,可以傳入任意個參數,包括0個參數:

def calc(*numbers):

sum = 0

for n in numbers:

sum = sum + n * n

return sum

calc(*nums)

5.unpacking argument lists

>>> list(range(3, 6)) # normal call with separate arguments

[3, 4, 5]

>>> args = [3, 6]

>>> list(range(*args)) # call with arguments unpacked from a list

[3, 4, 5]

有點像指針,第2個函數調用時,如果不使用*,range得到的是一個數組,需要將這個數組分解為2 個參數再傳遞給range()。

類似的,使用**也可以解包dictionaries形式的參數。

>>> def parrot(voltage, state=‘a stiff‘, action=‘voom‘):

... print("-- This parrot wouldn‘t", action, end=‘ ‘)

... print("if you put", voltage, "volts through it.", end=‘ ‘)

... print("E‘s", state, "!")

...

>>> d = {"voltage": "four million", "state": "bleedin‘ demised", "action": "VOOM"}

>>> parrot(**d)

-- This parrot wouldn‘t VOOM if you put four million volts through it. E‘s bleedin‘ demised !

2.2. lambda expressions

>>> def make_incrementor(n):

... return lambda x: x + n

...

>>> f = make_incrementor(42)

>>> f(0)

42

>>> f(1)

43

make返回的是一個函數,因此f是一個函數。

>>> f

<function make_incrementor.<locals>.<lambda> at 0x0000006D285F2E18>

>>> f(4)

46

盡量少這麽寫,寫多了總會坑人的。

2.3. document strings

常用案例:

>>> def my_function():

... """Do nothing, but document it.

...

... No, really, it doesn‘t do anything.

... """

... pass

...

>>> print(my_function.__doc__)

Do nothing, but document it.

No, really, it doesn‘t do anything.

2.4. function annotations

函數註釋,沒搞太明白。

>>> def f(ham: str, eggs: str = ‘eggs‘) -> str:

... print("Annotations:", f.__annotations__)

... print("Arguments:", ham, eggs)

... return ham + ‘ and ‘ + eggs

...

>>> f(‘spam‘)

Annotations: {‘ham‘: <class ‘str‘>, ‘return‘: <class ‘str‘>, ‘eggs‘: <class ‘str‘>}

Arguments: spam eggs

‘spam and eggs‘

筆記-python-tutorial-4.controlflow( and function)