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'
>>>