第八章 函数
函数的定义
def print_name(username):
print(username+"太强了,我是伞兵")
print_name("卢姥爷")
在函数定义中有多个形参时,调用函数时的输入实参顺序显然是和形参一一对应的,但是可以用以下方法规定哪一个实参传递给哪一个形参。如下所示:
def print_name(username,friend):
print(username+"是"+friend+"最好的朋友")
print_name("卢姥爷","凯亚")
print_name(friend="卢老爷",username="凯亚")
可见,可以使用关键字实参,规定实参传递给哪一个形参,而与输入顺序无关。
默认形参参数:
def print_name(username,friend="凯亚"):
print(username+"是"+friend+"最好的朋友")
print_name("卢姥爷")
这样是没啥问题的,此处应该是要求和C++保持一致,无默认值的形参要写在前面,有默认值的要写在后面。
def print_name(friend="凯亚",username):
print(username+"是"+friend+"最好的朋友")
print_name("卢姥爷")
这样的代码将会编译报错,报错信息如下,证明了我们的结论:
函数返回值的使用
def add_function(a, b):
return a + b
def name_produce(firstname, secondname):
return (firstname.title() + " " + secondname)
c = add_function(1, 2)
print(c)
wangxiaoming = name_produce("wang", "xiaoming")
print(wangxiaoming)
禁止函数修改列表:
def delete_List(list_p):
while list_p:
number=list_p.pop(0)
print(number)
list_p=["123","234","3124","314125"]
delete_List(list_p[:])#如果这里用的是list_p本身,则由于是引用传递。
#list_p本身的数据会被修改。
print(list_p)
传递任意数量的实参:
有些时候,传递的参数数量是不确定的,可以采用接下来的办法:
def delete_List(*list_p):
for number in list_p:
print(number,end=" ")
delete_List(1,2,3,4,5,6,7,8,9,10)
如果我们使用print(list_p)
可以看到 list_p是一个元组类型的数据
使用type函数也可以看出,类型是tuple
这里针对于元组tuple有一个问题,虽然大家都说元组元素不可以改变,但实际上我们可以查看下列代码:
def delete_List(*list_p):
print(type(list_p))
list_p[2].insert(0,12)
print(list_p)
delete_List(('lee', 21), ('gong', 20),[1,2,3])
实际上元组的元素发生了改变,我们可以认为是元组中元组地址和对应的数据的映射是不可改变的,但是对应的数据本身可以改变。
位置形参与任意数量实参相结合比较简单,只需要确保接受不确定数量的实参的形参在后面就可以了。
接下来我们看一下使用任意数量的关键字实参。
(意思就是,实参数量不确定,并且指定了关键字)
如下:
from functools import cmp_to_key
def key_judge(x,y):
if x[0]>y[0]:
return -1
else:
return 1
def produce_List(name, **list_p):
list_p["name"] = name
return list_p
newstudent = produce_List("Yin", school=</