把一切组合起来
- 你现在已经会变量、输入、
if、循环、列表、函数和字典了。 - 一个真正的程序会把这些小部件组合成一个有用的工具。
- 这节课你将一次写一个函数,搭出一个小小的班级成绩分析器。
计划
- 我们有一个成绩列表,比如
[70, 90, 50, 80]。 - 我们想要三个答案:平均分、有多少人及格,以及一段简短的总结。
- 我们会为每件事写一个小函数,然后让它们协同工作。
The analyzer calls each helper
A big program calls small functions in turn, each returning one answer.
处理列表的便捷内置函数
- Python 提供了一些现成的小助手,可以直接用在数字列表上。
len(x)数有多少个,sum(x)求和,max(x)/min(x)找出最大 / 最小值。- 用它们,而不必每次都自己写一个循环。
scores = [70, 90, 50, 80]
print(len(scores)) # 4
print(sum(scores)) # 290
print(max(scores)) # 90
print(min(scores)) # 50
一个你会反复用到的套路:统计通过测试的元素
- 一个很常见的任务:遍历一个列表,统计有多少元素通过某个测试。
- 将计数器初始化为
0,每当if为真时加1。 - 这里我们统计长单词;很快你就会去统计及格的成绩。
def how_many_long_words(words, min_length):
count = 0
for w in words:
if len(w) >= min_length:
count = count + 1
return count
print(how_many_long_words(["hi", "hello", "hey", "howdy"], 4)) # 2
常见错误
- 小块构建,每写好一块就测试,再加下一块。
- 先读完整个题目,规划好再写代码。
现在轮到你
- 分三步搭出分析器:
average、count_passing,然后stats。 - 每个函数都很小。它们合在一起,就能把一个成绩列表变成真正的答案。
- 每完成一个就按检查答案。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write average(scores) that returns the average (mean) of a list of numbers: the total divided by how many. If the list is 空的, return 0 (so it does not crash). Example: average([2, 4]) is(是) 3.0.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write count_passing(scores, pass_mark) that returns how many scores are greater than or equal to pass_mark. Loop the list and count. Example: count_passing([40, 50, 60], 50) is(是) 2.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write stats(scores) (assume at least one score) that returns a dictionary with three keys: "highest", "lowest", and "average". Example: stats([70, 90, 50, 80]) 返回值 {"highest": 90, "lowest": 50, "average": 72.5}.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write grade_counts(scores) that 返回值 a dictionary counting grades: A for 80 and above, B for 60 and above, C for the rest. Always include all three keys: grade_counts([85, 72, 90, 40]) is(是) {"A": 2, "B": 1, "C": 1}.
点击“运行”查看此处输出。