函数的创建
>>> def MyFirstFunction():
print('这是我创建的第一个函数!')
print('我表示很鸡冻……')
>>> MyFirstFunction()
这是我创建的第一个函数!
我表示很鸡冻……
>>> def add(x,y):
return(x + y)
>>> add(3,4)
7
收集参数
>>> def test(*params):
print('参数的长度是:',len(params))
print('第二个参数是',params[1])
>>> test(1, 'test' ,2,3,4)
参数的长度是: 5
第二个参数是 test
>>> def test(*params,exp):
print('参数的长度是:',len(params))
print('第二个参数是',params[1])
>>> test(1, 'test' ,2,3,exp = 4)
参数的长度是: 4
第二个参数是 test
统计字符串个数
def count(*parase):
numbers = '1234567890'
paradase = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
enter = ' '
i = 1
for each in parase:
count1,count2,count3 = 0,0,0
for every in each:
if every in numbers:
count1 += 1
elif every in paradase:
count2 += 1
elif every in enter:
count3 +=1
count4 = len(each) - count1 -count2 - count3
print('个字符串里共有:英文',count2,'个,数字',count1,'个,空格',count3,'个,其他字符',count4,'个')
i +=1
闭包
>>> def FunX(x):
def FunY(y):
return x *y
return FunY
>>> i = FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x000001F540DB3B80>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40
列表不是存放在栈里的和nonlocal关键字
>>> def Fun1():
x = [5]
def Fun2():
x[0] *= x[0]
return x[0]
return Fun2()
>>> Fun1()
25
>>> def Fun1():
x = 5
def Fun2():
nonlocal x
x *= x
return x
return Fun2()
>>> Fun1()
25
lambda表达式
>>> def ds(x):
return x * 2 + 1
>>> ds(5)
11
>>> g = lambda x : 2 * x + 1
>>> g(5)
11
filter 函数
>>> list(filter(None,[1,0,False,True]))
[1, True]
>>> def odd(x):
return x % 2
>>> temp = range(10)
>>> show = filter(odd, temp)
>>> list(show)
[1, 3, 5, 7, 9]
>>> list(filter(lambda x : x % 2,range(10)))
[1, 3, 5, 7, 9]
map函数
>>> list(map(lambda x : x * 2 ,range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]