三小时快速入门Python第五篇--异常处理与迭代器

异常处理与迭代器

1、异常处理

复制代码
 1 # 使用 try/except 代码块来处理异常
 2 # 自 Python 2.6 以上版本支持:
 3 try:
 4     # 使用 "raise" 来抛出一个异常
 5     raise IndexError("This is an index error")
 6 except IndexError as e:
 7     pass    # Pass 表示无操作. 通常这里需要解决异常.
 8 except (TypeError, NameError):
 9     pass    # 如果需要多个异常可以同时捕获
10 else:   # 可选项. 必须在所有的except之后
11     print("All good!")   # 当try语句块中没有抛出异常才会执行
12 finally: # 所有情况都会执行
13     print("We can clean up resources here")
14 
15 # with 语句用来替代 try/finally 简化代码
16 with open("myfile.txt") as f:
17     for line in f:
18         print (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()
 7 print(our_iterable)  # => dict_keys(['one', 'two', 'three']). 这个是实现了迭代器接口的一个对象.
 8 
 9 # 我们可以循环遍历.
10 for i in our_iterable:
11     print(i)  # 输出为: one, two, three
12 
13 # 然而我们并不能通过下标进行访问 所以要用迭代器来进行访问
14 our_iterable[1]  # 会报错 Raises a TypeError
15 
16 # An iterable is an object that knows how to create an iterator.
17 # 定义一个名字叫our_iterator的迭代器,实际上有点类似于指针,指向 our_iterable 这个的第一个元素
18 our_iterator = iter(our_iterable)
19 
20 # 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"
24 
25 # It maintains state as we iterate.
26 # 继续迭代
27 next(our_iterator)  # => "two"
28 next(our_iterator)  # => "three"
29 
30 # After the iterator has returned all of its data, it gives you a StopIterator Exception
31 # 迭代结束
32 next(our_iterator)  # Raises StopIteration
33 
34 # You can grab all the elements of an iterator by calling list() on it.
35 # 可以将这个强制转换成list
36 list(filled_dict.keys())  # => Returns ["one", "two", "three"]
复制代码

 上一篇:三小时快速入门Python第四篇--函数与对象

 下一篇:三小时快速入门Python终结篇--其他模块导入

posted @   小尾学长  阅读(622)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!
点击右上角即可分享
微信分享提示