毕业挑战 · Python 从零开始
能不能把学过的全部内容组合成一个真正的程序?
课程目录为什么需要它
会用每一样工具,不等于能做出东西。真实的程序把输入、列表、循环、判断和函数混在一起用。这一课先带你规划一个程序,再请你独立完成一个成绩册。做完它,Python 从零开始就毕业了。
直觉理解
动手之前先规划。几乎所有小程序都是同一个结构:
- 输入:有哪些数据进来?顺序是什么?
- 处理:要算什么?每个计算都写成一个小函数。
- 输出:每一行到底要打印什么?
然后一小步一小步地写,每写一步就运行一次。不要一口气写 30 行再碰运气。
成绩册就是:输入 = n 个分数;处理 = 个数、平均分、最高分、最低分、平均分对应的等级;输出 = 带标签的五行。
定义
分解 Decomposition
Decomposition is breaking a program into smaller functions, each solving one part of the problem.分解是把程序拆成更小的函数,每个函数解决问题的一部分。
增量开发 Incremental development
Incremental development means writing a program in small steps and testing after each step.增量开发是指一小步一小步地写程序,每一步之后都进行测试。
示例
购物总价,一步一步来
动手试试输入、用函数处理、输出。改改「输入」框再运行。
def read_prices():
n = int(input())
prices = []
for i in range(n):
prices.append(float(input()))
return prices
def total_with_discount(prices):
total = sum(prices)
if total > 15:
total = total * 0.9
return round(total, 2)
prices = read_prices()
print(f"Items: {len(prices)}")
print(f"Total: {total_with_discount(prices)}")输入(每次 input() 读一行)
3 4.5 2 10
逐步执行
- L14输入:read_prices() 先读 n,再读 n 个价格。
prices = [4.5, 2.0, 10.0] - L9处理:总和是 16.5。
total = 16.5 - L11超过 15,打九折:14.85。
total = 14.85 - L16输出:两行带标签的结果。
Total: 14.85
数字换成等级
动手试试一个用 if/elif 的小函数,先单独测好再拿去用。
def letter(avg):
if avg >= 80:
return "A"
elif avg >= 65:
return "B"
elif avg >= 50:
return "C"
return "F"
for test in [95, 70, 50, 10]:
print(test, letter(test))逐步执行
- L10在放进真正的程序之前,先用几个值测试这个函数。
- L395:第一个 return 就以 "A" 结束了函数。
95 A - L810:没有条件匹配,最后一行返回 "F"。
10 F
常见错误
一口气全写完
写一块,运行一次,再加下一块。出问题时你就能准确知道是哪一部分。
输出差一点点
判题是逐字比较的:Average:71.7 不等于 Average: 71.7。标签要仔细照抄。
小测验
1. 这段代码会输出什么?
def stats(xs):
return min(xs), max(xs)
low, high = stats([4, 9, 1])
print(high - low)查看答案
答案:A
函数可以返回两个值;这里是 1 和 9,所以 9 − 1 = 8。
2. 这段代码会输出什么?
print(round(71.666, 1), round(80.0, 1))查看答案
答案:A
round(x, 1) 保留一位小数并四舍五入:71.666 → 71.7;80.0 仍是 80.0。
动手练习
3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。
- 预测输出trace 一个完整程序
准确写出程序的输出。
- 改需求加一条折扣规则
修改
total_with_discount:超过 15 仍然打九折,但超过 50 打八折。保留round(..., 2)。 - 从零写毕业作品:成绩册
读入 n,再读入 n 个整数分数。准确打印五行:
Count: 3 Average: 71.7 Highest: 90 Lowest: 55 Grade: B- 平均分用
round(avg, 1)保留一位小数。 - 等级按平均分算:80 以上 A,65 以上 B,50 以上 C,其余 F。
- 至少写一个你自己的函数(比如
letter(avg))。
- 平均分用
本课术语
| 术语 | 中文 | 英文定义 |
|---|---|---|
| Decomposition | 分解 | Breaking a program into smaller functions that each solve one part. |
| Incremental development | 增量开发 | Writing a program in small steps and testing after each one. |
| round() | round() 四舍五入 | A built-in that rounds a number to a given number of decimal places. |