1# 使用 try/except 代码块来处理异常 2# 自 Python 2.6 以上版本支持: 3try:
4# 使用 "raise" 来抛出一个异常 5raise IndexError("This is an index error")
6except IndexError as e:
7pass# Pass 表示无操作. 通常这里需要解决异常. 8except (TypeError, NameError):
9pass# 如果需要多个异常可以同时捕获10else: # 可选项. 必须在所有的except之后11print("All good!") # 当try语句块中没有抛出异常才会执行12finally: # 所有情况都会执行13print("We can clean up resources here")
1415# with 语句用来替代 try/finally 简化代码16 with open("myfile.txt") as f:
17for line in f:
18print (line)
2、迭代器
1# Python提供了一个称为Iterable的迭代器。 2# iterable是可以作为序列处理的对象。 3# 返回范围函数的对象是iterable。 4 5 filled_dict = {"one": 1, "two": 2, "three": 3}
6 our_iterable = filled_dict.keys()
7print(our_iterable) # => dict_keys(['one', 'two', 'three']). 这个是实现了迭代器接口的一个对象. 8 9# 我们可以循环遍历.10for i in our_iterable:
11print(i) # 输出为: one, two, three1213# 然而我们并不能通过下标进行访问 所以要用迭代器来进行访问14 our_iterable[1] # 会报错 Raises a TypeError1516# An iterable is an object that knows how to create an iterator.17# 定义一个名字叫our_iterator的迭代器,实际上有点类似于指针,指向 our_iterable 这个的第一个元素18 our_iterator = iter(our_iterable)
1920# Our iterator is an object that can remember the state as we traverse through it.21# We get the next object with "next()".22# 获取这个迭代器所指的值 用next 输出后 our_iterator 指向下一个元素23 next(our_iterator) # => "one"2425# It maintains state as we iterate.26# 继续迭代27 next(our_iterator) # => "two"28 next(our_iterator) # => "three"2930# After the iterator has returned all of its data, it gives you a StopIterator Exception31# 迭代结束32 next(our_iterator) # Raises StopIteration3334# You can grab all the elements of an iterator by calling list() on it.35# 可以将这个强制转换成list36 list(filled_dict.keys()) # => Returns ["one", "two", "three"]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!