Files
PythonLearn/02_python进阶/2_7_类型注解/practice.py

85 lines
3.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第 2-7 课课堂练习:类型注解
#
# 请先阅读讲义并运行完整示例,再按照题目顺序完成。
# 每个函数都需要写参数类型和返回值类型。
# 不要删除题目、测试数据、预期结果和自查注释。
# 第一部分:定义 format_task_status(title, completed) 函数
# 1. 参数 title 标注为 str。
# 2. 参数 completed 标注为 bool。
# 3. 返回值标注为 str。
# 4. completed 为 True 时状态文字是“已完成”,否则是“未完成”。
# 5. return f"{title}|状态:{status_text}"。
# 6. 传入“学习类型注解”和 True预期返回
# “学习类型注解|状态:已完成”。
# print(format_task_status("学习类型注解", True))
# 第二部分:定义 build_task(title, status) 函数
# 1. 两个参数都标注为 str。
# 2. 返回值标注为 dict[str, str]。
# 3. return 包含 title 和 status 的新字典。
# 4. 传入“复习生成器”和“未开始”,预期返回:
# {"title": "复习生成器", "status": "未开始"}。
# print(build_task("复习生成器", "未开始"))
# 第三部分:定义 get_task_titles(tasks) 函数
# 1. 参数标注为 list[dict[str, str]]。
# 2. 返回值标注为 list[str]。
# 3. 使用列表推导式取得每个任务的 title。
# 4. return 新列表,不要修改原 tasks。
# 5. 使用顶部测试数据,预期返回:
# ["学习类型注解", "完成课堂练习"]。
# print(get_task_titles(tasks))
# 第四部分:定义 calculate_completion_rate(completed_count, total_count) 函数
# 1. 两个参数都标注为 int。
# 2. 返回值标注为 float | None表示可能返回浮点数也可能返回 None。
# 3. total_count 为 0 时 return None。
# 4. 否则 return completed_count / total_count。
# 5. 传入 3 和 4预期返回 0.75。
# 6. 传入 0 和 0预期返回 None程序不能崩溃。
# print(calculate_completion_rate(3,4))
# print(calculate_completion_rate(0,0))
# 第五部分:定义 print_task(task) 函数
# 1. 参数标注为 dict[str, str]。
# 2. 返回值标注为 None因为本函数只输出不返回业务结果。
# 3. 按“任务:标题|状态:状态文字”的格式输出。
# 4. 传入第一个测试任务,预期输出:
# “任务:学习类型注解|状态:已完成”。
# print_task(tasks[0])
# 第六部分:定义 main() 函数
# 1. 返回值标注为 None。
# 2. 依次调用前面五个函数,并保存需要使用的返回值。
# 3. 输出格式化状态、新任务字典、任务标题列表和两种完成率。
# 4. 调用 print_task(tasks[0]) 输出第一个任务。
# 5. 添加程序入口判断,直接运行本文件时调用 main()。
# 最终验收测试:
# 1. format_task_status() 的参数和返回值注解正确;
# 2. build_task() 返回正确字典,并标注 dict[str, str]
# 3. get_task_titles() 返回正确列表,并标注 list[str]
# 4. calculate_completion_rate(3, 4) 返回 0.75
# 5. calculate_completion_rate(0, 0) 返回 None
# 6. 完成率返回类型标注为 float | None
# 7. print_task() 和 main() 的返回值标注为 None
# 8. 原始 tasks 没有被修改;
# 9. 直接运行程序时,所有结果均正确输出。
# 完成后自查:
# 1. 是否知道冒号后写参数或变量类型;
# 2. 是否知道 -> 后写函数返回值类型;
# 3. 是否能区分 list[str] 和 dict[str, str]
# 4. 是否理解 float | None 表示两种可能结果;
# 5. 是否知道只输出的函数返回值标注为 None
# 6. 是否理解类型注解通常不会自动检查运行时数据;
# 7. 是否保留了完整题目和验收说明。