Python 控制流与异常处理深入解析
1. 控制流概述
程序的控制流是指程序在执行过程中所遵循的路径。常见的控制流结构包括顺序结构、 if 、 for 和 while 块,它们用于管理代码中的基本分支。本文将聚焦于一些不太常用但同样重要的控制流机制。
2. 异常捕获
在 Python 中,当期望被违反时,鼓励使用异常处理。异常的抛出使用 raise 关键字,而捕获异常则稍微复杂一些,需要结合多个关键字。
- 基本异常捕获 :
def count_lines(filename):
"""
Count the number of lines in a file. If the file can't be
opened, it should be treated the same as if it was empty.
"""
try:
return len(open(filename, 'r').readlines())
except:
print('exception error reading the file or calculating lines!')
return 0
myfile = input('Enter a file to open: ')
print(count_lines(my
订阅专栏 解锁全文
2万+




被折叠的 条评论
为什么被折叠?



