# 函数四

### 函数

#### 回顾

num = int(10)      # 内置变量   B
# num = 20         # 全局变量   G
def outer():
# num = 30     # 闭包变量   E
def inner():
# num = 40 # 局部变量   L
print(num)
return inner
i = outer()
i()


l = ["pY","IS","eASY"]
bs_list =  [x.swapcase() for x in l]
print(bs_list)


#### 迭代器

1> list,set,tuple,dict,string

2> generator[生成器] 【第一种形式: (),函数结合yield】

def lg(num):
for i in range(1,num):
yield i
l = lg(10)
# 生成器保存是算法，而列表保存内容是在内存中,列表不占优势,耗内存，生成器节约内存开销
print(sum(l))
# 生成器只被使用一次
print(sum(l))

gs = (x for x in range(1,10))

from collections.abc import Iterable
isinstance(gs,Iterable)


['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']


#### 装饰器

def demo():
print("demo func")
def func():
print("demo func")
print("func")
func()

# y是形参，是函数
def demo(y):
print("demo func")
y()
@demo
def func():
print("func")
func是实参


def demo(func):
def inner(age):
if age<=10:
mystr = "children"
elif age <= 20:
mystr = "midman"
else:
mystr = "oldman"
return func(mystr)
return inner

@demo
def func(p):
print("你是一个这样的",p)

#　调用
func(60)



#### 栈和队列

##### 栈

my_stack = []
# 向栈进入数据
my_stack.append(23)
my_stack.append(22)
my_stack.append(21)
my_stack.append(20)
my_stack.append(19)
print(my_stack)

my_stack.pop()
print(my_stack)
my_stack.pop()
print(my_stack)
my_stack.pop()
print(my_stack)
my_stack.pop()
print(my_stack)
my_stack.pop()
print(my_stack)

[23, 22, 21, 20, 19]
[23, 22, 21, 20]
[23, 22, 21]
[23, 22]
[23]
[]

##### 队列

import collections
queue = collections.deque([1,20,25,40])
print(queue)
# 入队一年
queue.append(68)
print(queue)
queue.append(77)
print(queue)

# 出队
queue.popleft()
print(queue)
queue.popleft()
print(queue)

##### 闭包

1.内层函数定义在外层函数之内

2.内层函数引用外层的参数进行设定特定的功能

3.外层函数返回内层函数名

4.如a=f()通过配合赋值运算将外层的返回值，也就是将内层的函数名赋给a

5.通过这变量a来间接调用内层函数

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客