3/06课后总结
异常捕获补充
try :
print (ekaskl)
except Exception as e:
print (e)
else :
print ('没得问题' )
finally :
print ('反正都行' )
try :
print (1 )
except Exception as e:
print (e)
else :
print ('没得问题' )
finally :
print ('反正都行' )
for循环原理补充
l = [1 , 2 , 3 , 4 , 5 ]
res = iter (l)
while True :
try :
print (next (res))
except Exception:
break
"""
注释掉的for循环的底层逻辑就是while循环
"""
生成器对象
def index ():
print (1 )
yield 1111
print (2 )
print (3 )
yield 2222
print (4 )
print (5 )
yield 3333
print (6 )
res = index()
ret = res.__next__()
print (ret)
ret = res.__next__()
print (ret)
ret = res.__next__()
print (ret)
"""
函数中存在yield,在调用前是普通函数,调用后就变成了生成器(迭代器)
"""
生成器的案例:实现range方法
def my_reang (x, y=None , z=1 ):
if not y:
y = x
x = 0
while x < y:
yield x
x += z
while x > y:
yield x
x -= z
for i in my_reang(2 , 20 , 1 ):
print (i)
yield传值(了解)
def eat ():
print ('开始干饭' )
while True :
food = yield
print ('吃%s' % food)
res = eat()
print (res.__next__())
res.send('锅巴' )
res.send('锅巴1' )
res.send('锅巴2' )
yield与return的对比
yield :
1. 可以有返回值
2. 把函数停住,不结束
3. 把函数变成生成器,支持__next__取值
return :
1. 可以有返回值
2. 结束函数的运行
生成器表达式
def add (n, i ):
return n + i
def test ():
for i in range (4 ):
yield i
g = test()
for n in [1 , 10 , 11 ]:
g = (add(n, i) for i in g)
"""
第一次循环:
g = (add(1, i) for i in g)
第二次循环:
g = (add(n, i) for i in (add(n, i) for i in g))
"""
res = list (g)
print (res)
常见内置函数
l = [1 , 2 , 3 , 0 ]
abs (-1 )
all (l)
any (l)
myslice = slice (5 )
divmod (100 , 10 )
eval ()
exec ()
isinstance ('123' , int )
chr (65 )
ord ('A' )
sum ()
pow ()
res=bytes (s, 'utf-8' )
callable (index)
round (3.4 )
locals ()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!