函数

 函数的优点:1减少重复代码 ;2保持一致性,易维护;3可扩展

#过程:就是没有返回值(return)的函数
# def test01():
# msg = 'hello The littlt green frog'
# print(msg)


#函数:有return返回值
# def test02():
# msg = 'hello wudalang'
# print(msg)
# return msg

# def test03():
# msg = 'hello llll'
# print(msg)
# return 1,2,3,4,'alex',['jack'],{'guangdong':'tianhe'}

# t1 = test01()
# t2 = test02()
# t3 = test03()
# print(t1)
# print(t2)
# print(t3)


# def calc(x,y):
# res = x ** y
# return res
# res = calc(2,3)
# print(res)
# # a = 10
# # b = 10
# # calc(a,b)

#位置参数
# def test(x,y,z):
# print(x)
# print(y)
# print(z)
# test(1,2,3)#位置参数必须一一对应,多一不可,缺一也不可
# test(y = 1,x = 3,z = 2)#关键字参数无需一一对应,但缺一不可,多一也不可
#如果混合使用,位置参数必须在关键字参数左边
#test(1,y = 2,3)结果报错
#test(1,3,y = 2)结果报错,因为位置参数3已经赋值给y了,与后面的y=2冲突,而且还缺少z的值


# def handle(x,type = 'mysql'):
# print(x)
# print(type)
# handle('handle')
# handle('hello', 'sqlite')

def test(x,*args,**kwargs):#无所不能的形式,可以接受任何参数
print(x)
print(args)
print(kwargs)
test(11,2,3,4,5,6,7,7,y=2,j=3)--也可以直接接受列表和字典:test(11,*[2,3,4,5,6,7,7],**{'y':2,'j':3})
#输出结果:
11
(2, 3, 4, 5, 6, 7, 7)
{'y': 2, 'j': 3}


原文地址:https://www.cnblogs.com/lhqlhq/p/8661926.html