Python函數及可變參數

Python函數及可變參數

函數返回值-函數被調用後會返回一個指定的值,默認返回None,函數可以定義return返回值,如果不定義,則默認無返回值,即返回值爲None,區分返回值和打印,return返回值與print沒有任何關係。

與其他語言一樣,函數如果定義了return,一旦執行到return就結束了,因此如果函數中同一邏輯塊定義多個return,也只有第一個return有效。另一方面,return語句後的語句都不會執行,請看下面case:

case2
def f(x,y):
	if x < y:
		return -1
	print("Hello World")

# output
>>> z=f(3,2)
Hello World
>>> print(z)
None
>>> type(z)
<type 'NoneType'>

函數可變參數

def fun(name,age=0):
    print(name,age)
    
fun('lily')
fun('lilei',30)
******output******
lily 0
lilei 30
>>> 

#字典dict類型數據裏面key-value直接傳遞給函數形參
d1={'name':'xixi','age':18}
fun(**d1)

d2={'name2':'dada','age2':20}
fun(**d2)
*******output*********** 字典key-value傳遞給形參,要求 1.形參名與key名一定要相同,否則報錯,見下case;
xixi 18
Traceback (most recent call last):
  File "D:/Program Files/Python36/var.py", line 14, in <module>
    fun(**d2)
TypeError: fun() got an unexpected keyword argument 'name2'
>>> 
*******case Input*********** 字典key-value傳遞給形參,要求 2.形參個數 與key 個數一定要相同,否則報錯,見下case;
d3={'name':'dada','age':20,'sex':'female'}
fun(**d3)
*******output***********
>>>Traceback (most recent call last):
  File "D:/Program Files/Python36/var.py", line 12, in <module>
    fun(**d3)
TypeError: fun() got an unexpected keyword argument 'sex'
>>> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章