导读:
本文主要记录自己学习python3基础中函数编程的要点知识和例子;仅供自己梳理
def 函数名(形参):
代码块
return
def func_test1():
print('大家晚上好')
# 定义函数:func_test2()
def func_test2(name):
str2 = name + ' 欧力给!'
# 返回函数处理结果:str2
return str2
# 调用函数:func_test2(),并传入实参:name='YDXQBJL'
print(func_test2('YDXQBJL'))
# 定义
def func_test3(name,age):
str3 = name + '的年龄是:' + age
return str3
# 调用
res = func_test3('爷的心情悲寂寥','18')
# 打印结果
print(res)
def func1(name,city):
str1 = 'I am {},I come from {}'.format(name,city)
return str1
res1 = func1('ydxqbjl','beijing')
print(res1)
res2 = func1('beijing','ydxqbjl')
print(res2)
def func2(name,city):
str2 = 'I am {},I come from {}'.format(name,city)
return str2
res1 = func2(name='ydxqbjl',city='beijing')
print(res1)
res2 = func2(city='beijing',name='ydxqbjl')
print(res2)
def func3(name,city = 'china'):
str3 = 'I am {},I come from {}'.format(name,city)
return str3
res3 = func3(name='ydxqbjl')
print(res3)
通过给形参前面添加 * 使参数变成一个元组,所有传递的参数变成元组的元素
def func4_1(*args):
print(args)
func4_1()
func4_1(1,2)
func4_1(1,2,3,4,'asfd')
通过给形参前面添加 ** 使参数变成一个字典,所有传递的参数变成字典的键值对,返里传参要求键等 于值的形式
def func4_2(**kwargs):
print(kwargs)
func4_2()
func4_2(a = 1)
func4_2(a=1,b=2,c=3)
def funcName(e,f,g=2,*args,**kwargs):
a = args
b = kwargs
re = e,f,g,a,b
return re
response1 = funcName(1,2)
print(response1)
response2 = funcName(1,2,3,a=1)
print(response2)
response3 = funcName(1,2,3,4,a=1)
print(response3)
response4 = funcName(1,2,3,4,5,6,7,a=1,b=2,c=3)
print(response4)
L = lambda x:x*x
print(L(5))
25
L = lambda x : 'x>10' if x >10 else 'x<10'
print(L(5))
如果用函数实现的话:
def L(x):
if x >10:
return 'x>10'
else:
return 'x<10'
print(L(11))
普通函数写法:
lista = [1,2,3,4]
listb = []
def funcpf(x):
return x*x
for i in lista:
listb.append(funcpf(i))
print(listb)
使用map()函数后:
def funcpf(x):
return x*x
res1 = map(funcpf,[1,2,3,4])
print(list(res1))
使用lambda后:
res = map(lambda x:x*x,[1,2,3,4])
print(list(res))
a = [1,2,3]
b = [4,5,6]
c = map(lambda x,y:x+y,a,b)
print(list(c))
注意:即使lambda简洁好用,但是不建议大家滥用。用多了,程序可读性很差。