数据 Analyzer
你将构建什么
Python script 那个 takes 列表的 数字 and computes 平均值, 中位数, 模式, 最小值, 最大值, and 标准 deviation, 然后 prints 格式化 report.
学习目标
- Use statistics 模块 for 平均值, 中位数, 模式
- Compute 最小值, 最大值, and 范围 manually
- 格式输出使用 f-字符串 and alignment
- Handle 空列表 gracefully
前置要求
- 列表 and 列表方法
- 函数使用参数
- Importing 模块
步骤
- 1
导入 statistics and 定义 analyzer
导入 statistics 模块 and 定义 analyze(数据) 那个 takes 列表的 数字. Guard 针对空 列表通过 returning early 使用消息.
代码import statistics def analyze(data): if not data: return "No data to analyze" results = {} results["count"] = len(data) results["mean"] = statistics.mean(data) results["median"] = statistics.median(data) return results预期结果
analyze([1, 2, 3, 4, 5]) 返回 dict 使用数量, 平均值, and 中位数.
- 2
添加更多 statistics
Extend 函数到 compute 最小值, 最大值, 范围, and 标准 deviation. Use try/except for 模式由于它 能 raise StatisticsError for multimodal 数据.
代码results["min"] = min(data) results["max"] = max(data) results["range"] = max(data) - min(data) results["stdev"] = statistics.stdev(data) if len(data) > 1 else 0 try: results["mode"] = statistics.mode(data) except statistics.StatisticsError: results["mode"] = "no unique mode"预期结果
results dict 现在包含最小值, 最大值, 范围, stdev, and 模式.
- 3
Print 格式化 report
Print 每个 statistic 使用 label, aligned using f-字符串宽度 specifiers. Call analyze 使用 sample 数据 and print results.
代码def print_report(data): results = analyze(data) if isinstance(results, str): print(results) return print("=== Data Analysis Report ===") for key, value in results.items(): print(f"{key:>10}: {value}") print_report([10, 20, 20, 30, 40, 50])预期结果
格式化 report showing 数量, 平均值, 中位数, 最小值, 最大值, 范围, stdev, and 模式.
- 4
添加输入验证与异常处理
在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。
代码def safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)预期结果
非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。
- 5
编写单元测试
使用 unittest 或 assert 语句为核心函数编写测试,覆盖正常路径、边界值和异常情况。测试是保证代码质量的安全网。
代码import unittest class TestCoreFunc(unittest.TestCase): def test_normal(self): self.assertEqual(core_func(5), expected_5) def test_boundary(self): self.assertEqual(core_func(0), expected_0) def test_exception(self): with self.assertRaises(ValueError): core_func(-1) if __name__ == "__main__": unittest.main()预期结果
运行 python test.py 后输出 OK,三个测试用例全部通过。
自己动手试试
import statistics
# TODO: define analyze(data) and print_report(data)
# Then test with: print_report([10, 20, 20, 30, 40, 50])
import statistics
def analyze(data):
if not data:
return "No data to analyze"
results = {}
results["count"] = len(data)
results["mean"] = statistics.mean(data)
results["median"] = statistics.median(data)
results["min"] = min(data)
results["max"] = max(data)
results["range"] = max(data) - min(data)
results["stdev"] = statistics.stdev(data) if len(data) > 1 else 0
try:
results["mode"] = statistics.mode(data)
except statistics.StatisticsError:
results["mode"] = "no unique mode"
return results
def print_report(data):
results = analyze(data)
if isinstance(results, str):
print(results)
return
print("=== Data Analysis Report ===")
for key, value in results.items():
print(f"{key:>10}: {value}")
print_report([10, 20, 20, 30, 40, 50])你学到了什么
你 used statistics 模块, handled 边缘情况 (空列表, multimodal 数据), and 格式化输出 — 基础的 数据 analysis scripts.
相关资源
相关练习
- 列表 Slicing 测验
练习列表操作.
- Predict 列表方法输出
Predict 列表方法.
相关速查表
- Python Cheatsheet
Statistics and 列表引用.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。