python中的函式1

2021-08-11 07:00:30 字數 1544 閱讀 6750

1.定義函式的時候可以在傳引數的時候設定乙個預設值,不過只能在最後的乙個引數設定預設值,比如:

def say(what,time=1):

print(what*time)

say('hi')

say('hi',3)

2.函式中的可變引數,*param 代表引數是個元組,**param代表引數是個字典

>>> def total(a=5,*numbers,**people):

...     print('a',a)

......     for single_item in numbers:

...         print('single_item',single_item)

......     for name,age in people.items():

...         print(name,age)

...>>> print(total(10,1,2,3,jack=23,john=25,inge=26))

('a', 10)

('single_item', 1)

('single_item', 2)

('single_item', 3)

('inge', 26)

('john', 25)

('jack', 23)

none

3.python中有乙個文件字串的功能,通過呼叫 __doc__ 可以將函式中的說明列印出來,比如一下有個找出個函式

def print_max(x,y):

''' this function will find the max num 

print  maximum of the two num

the two number must be integer'''

x = int(x)

y = int(y)

if(x>y):

print('x is max')

else:

print('y is max')

print_max(3,5)

print(print_max.__doc__)

最終結果將列印以下內容:

y is max

this function will find the max num 

print  maximum of the two num

the two number must be integer

4.format方法

format放在字串之後,將方法中的引數替換到字串中的引數位置,比如

>>> name='uncle_king'

>>> what='python'

>>> print(' study '.format(name,what))

uncle_king study python

其中對應第乙個變數name,對應第二個變數 what,不過{}裡面的數字可以省略:

>>> print('{} study {}'.format(name,what))

uncle_king study python

Python中reshape函式引數 1的意思

a np.array 1,2 3 4,5,6 np.reshape a 3,1 the unspecified value is inferred to be 2 array 1,2 3,4 5 6 因為 a 總共有 6 個元素,reshape 成乙個二維陣列,指定第一維的長度是3 即 3 行 nu...

Python中reshape函式引數 1的使用

個人認為這是為了偷懶而設計的,為什這麼說呢,假設你有a 1 2 3 4 5 6 7 8 9 10 這樣的一維陣列,你只想讓a變成2列的二維陣列。按照常規的reshape,你得計算他的行數,經計算reshape的引數為reshape 5,2 而使用reshape 1,2 他會利用a和2列,計算出行數為...

Python 的函式定義1

留著這裡免得忘記了。媽媽的。誤刪了乙個連恢復都恢復不來了。這種定義方式看起來好記一些。def sum v1 int 2 v2 int 2 int v1 first operator v2 second operator return v1 v2 return v1 v2 def sum2 v1 v2...