Day 01——Task01:变量、运算符与数据类型
Day 02——Task02:条件与循环
Day 03——Task03:列表与元组(上)
Day 04——Task03:列表与元组(下)
Day 05——Task04:字符串与序列
Day 06——Task05:函数与Lambda表达式(上)
Day 07——Task05:函数与Lambda表达式(下)
Day 08——Task06:字典与集合
Day 09——Task07:文件与文件系统(上)
Day 10——Task07:文件与文件系统(下)
Day 11——Task08:异常处理
Day 12——Task09:else 与 with 语句
Day 13——Task10:类与对象(上)
Day 14——Task10:类与对象(下)
Day 15——Task11:魔法方法(上)
Day 16——Task11:魔法方法(下)
Day 17——Task12:模块
文章目录
1. else 语句
在Python中,else语句很与许多其他的语句进行联系。
1.1. if…else 语句
if...else
是我们最常见的带有else的语句,也相对简单。
try:
a = int(input("输入一个数字:"))
if a % 2 == 0:
print("这是个复数")
else:
print("这是个单数")
except:
print("输入错误")
1.2. while…else 语句
while
中的语句和普通的没有区别,else
中的语句会在循环正常执行完的情况下执行。
count = 0
while count < 5:
print("%d is less than 5" % count)
count = count + 1
else:
print("%d is not less than 5" % count)
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
# 4 is less than 5
# 5 is not less than 5
当while
循环被break
跳出时,else
子句也不会执行。
count = 0
while count < 5:
print("%d is less than 5" % count)
if count == 4:
break
count = count + 1
else:
print("%d is not less than 5" % count)
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
# 4 is less than 5
1.3. for … else 语句
for ... else
语句与 while ... else
语句一样,else
中的语句会在循环正常执行完的情况下执行。
for count in range(5):
print("%d is less than 5" % count)
if count == 4:
break
count = count + 1
else:
print("%d is not less than 5" % count)
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
# 4 is less than 5
1.4. try … except … else 语句
如果在 try
子句执行时没有发生异常,Python将执行 else
语句后的语句(如果有 else 的话),然后控制流通过整个 try 语句。
try:
正常的操作
......................
except:
发生异常,执行这块代码
......................
else:
如果没有异常执行这块代码
使用 except
而不带任何异常类型,这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息,因为它捕获所有的异常。
try:
正常的操作
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
发生以上多个异常中的一个,执行这块代码
......................
else:
如果没有异常执行这块代码
举个例子:
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.close()
# 内容写入文件成功
2. with 语句
一些对象定义了标准的清理行为,无论系统是否成功的使用了它,一旦不需要它了,那么这个标准的清理行为就会执行。
关键词 with
语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行它的清理方法。
try:
f = open('myfile.txt', 'w')
for line in f:
print(line)
except OSError as error:
print('出错啦!%s' % str(error))
finally:
f.close()
# 出错啦!not readable
这段代码执行完毕后,就算在处理过程中出问题了,文件 f
总是会关闭。
try:
with open('myfile.txt', 'w') as f:
for line in f:
print(line)
except OSError as error:
print('出错啦!%s' % str(error))
# 出错啦!not readable
参考资料
- https://blog.csdn.net/LSGO_MYP/article/details/102825466