feat(python进阶): 完成第三至第八课教学内容
This commit is contained in:
90
02_python进阶/2_3_异常处理/exception_example.py
Normal file
90
02_python进阶/2_3_异常处理/exception_example.py
Normal file
@@ -0,0 +1,90 @@
|
||||
# 第 2-3 课完整示例:异常处理
|
||||
#
|
||||
# 本程序通过固定测试数据演示异常处理,不会要求用户输入。
|
||||
# 文件示例只会读取当前课程目录中的 example_data 文件夹。
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
LESSON_DIR = Path(__file__).parent
|
||||
DATA_DIR = LESSON_DIR / "example_data"
|
||||
CONFIG_FILE = DATA_DIR / "agent_count.txt"
|
||||
|
||||
|
||||
def parse_positive_integer(number_text):
|
||||
"""把文本转换为正整数,失败时返回 None。"""
|
||||
try:
|
||||
number = int(number_text)
|
||||
except ValueError:
|
||||
# ValueError 表示值的内容不符合转换要求。
|
||||
print(f"“{number_text}”不是有效整数。")
|
||||
return None
|
||||
|
||||
if number <= 0:
|
||||
print("数字必须大于 0。")
|
||||
return None
|
||||
|
||||
return number
|
||||
|
||||
|
||||
def divide_tool_count(tool_count, agent_count):
|
||||
"""计算平均工具数量,除数为零时返回 None。"""
|
||||
try:
|
||||
average = tool_count / agent_count
|
||||
except ZeroDivisionError:
|
||||
# ZeroDivisionError 表示程序尝试用数字除以零。
|
||||
print("Agent 数量不能为 0。")
|
||||
return None
|
||||
else:
|
||||
# 只有 try 中没有发生异常时,才会执行 else。
|
||||
return average
|
||||
|
||||
|
||||
def read_agent_count(file_path):
|
||||
"""读取文件中的 Agent 数量,并保证输出结束提示。"""
|
||||
try:
|
||||
content = file_path.read_text(encoding="utf-8")
|
||||
return int(content.strip())
|
||||
except FileNotFoundError:
|
||||
print(f"没有找到文件:{file_path.name}")
|
||||
except ValueError:
|
||||
print(f"{file_path.name} 中保存的不是有效整数。")
|
||||
finally:
|
||||
# 无论是否发生异常,finally 都会执行。
|
||||
print(f"已完成对 {file_path.name} 的读取尝试。")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def prepare_example_file():
|
||||
"""在课程专用目录中准备安全的示例文件。"""
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
CONFIG_FILE.write_text("3\n", encoding="utf-8")
|
||||
|
||||
|
||||
def main():
|
||||
"""依次运行整数转换、除法和文件读取示例。"""
|
||||
print("一、处理整数转换异常")
|
||||
valid_number = parse_positive_integer("5")
|
||||
invalid_number = parse_positive_integer("五")
|
||||
print(f"有效结果:{valid_number}")
|
||||
print(f"无效结果:{invalid_number}")
|
||||
|
||||
print("=" * 30)
|
||||
print("二、处理除以零异常")
|
||||
average = divide_tool_count(6, 3)
|
||||
failed_average = divide_tool_count(6, 0)
|
||||
print(f"正常结果:{average}")
|
||||
print(f"异常结果:{failed_average}")
|
||||
|
||||
print("=" * 30)
|
||||
print("三、处理文件读取异常")
|
||||
prepare_example_file()
|
||||
agent_count = read_agent_count(CONFIG_FILE)
|
||||
missing_count = read_agent_count(DATA_DIR / "missing.txt")
|
||||
print(f"文件中的 Agent 数量:{agent_count}")
|
||||
print(f"不存在文件的读取结果:{missing_count}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user