写代码前先规划
- 算法(algorithm)是一份解决问题的清晰步骤清单。
- 优秀的程序员会在敲代码之前先规划好步骤。
- 规划能帮你及早发现错误,并把思路讲清楚。
分解
- 分解(decomposition)就是把一个大问题拆成更小的部分。
- 每个小部分单独解决。
- 小部分更容易编写、测试和修改。
抽象
- 抽象(abstraction)就是只保留重要的细节。
- 你把暂时不需要的部分隐藏起来。
- 地图就是一种抽象:它显示道路,而不是每一棵树。
结构化英语
- 结构化英语(structured English)用平实的编号句子来写步骤。
- 它不是真正的代码,所以任何人都能读懂。
1. Read the number.
2. If it can be divided by 2 with no remainder, it is even.
3. Otherwise it is odd.
4. Output the answer.
流程图
- 流程图(flowchart)把步骤画成用箭头连接的方框。
- 矩形表示一个步骤;菱形表示一个判断(是 / 否)。
三种基本结构
- 顺序(sequence):步骤一个接一个地执行。
- 选择(selection):
if/elif/else选择一条路径。 - 迭代(iteration):
for/while重复执行步骤。
用剑桥伪代码表示
- 先在伪代码中描述计划,再在下方用 Python 实现。考试中的数组通常从 1 开始索引,
Count存储数字的总个数。
Total ← 0
FOR I ← 1 TO Count
Total ← Total + Numbers[I]
NEXT I
Average ← Total / Count
OUTPUT Average
numbers = [4, 8, 6]
total = 0
for n in numbers:
total = total + n
average = total / len(numbers)
print(average)
常见错误
- 伪代码是用平白语言写的计划——不必能运行。
- 动手写代码前,先把问题拆成小步骤。
- 规划输入 → 处理 → 输出。
现在轮到你
- 每个任务都用文字给出一个规划。把它变成 Python。
- 按检查答案来测试你的代码。
算法就是有序的步骤
Pseudocode is just the steps in order, before you write real code.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Follow this plan: read a whole number; if it divides by 2 with no remainder print Even, otherwise print Odd. For input 4, print Even.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Follow this plan: read a number N; add up every whole number from 1 到 N; print the total. For input 5, print 15.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Decompose this into a function. Write count_vowels(word) that 返回值 how many letters of word are vowels (a e i o u, lowercase).
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Follow this plan for every number from 1 到 15: if it divides by both 3 and 5, print FizzBuzz; else if it divides by 3, print Fizz; else if it divides by 5, print Buzz; otherwise print the number.
点击“运行”查看此处输出。