用 for 重复
for循环会把代码重复固定的次数。- 循环体要缩进,就像
if一样。 - 循环变量在每一轮都会取一个新的值。
用 range 计数
range(5)给出数字0, 1, 2, 3, 4(到 5 之前停下)。range(1, 6)给出1, 2, 3, 4, 5(包含起点,不包含终点)。range(0, 10, 2)以 2 为步长计数。
for i in range(5):
print(i)
累加求和(累加器)
- 累加器(accumulator)是在循环里不断变大的变量。
- 在循环之前把它从
0开始。 - 每一轮都往里面加,从而得到累计总和。
total = 0
for n in range(1, 6):
total = total + n
print(total)
用剑桥伪代码表示
- Python 的
for … range循环就是考试里的计数循环FOR … NEXT。
Total ← 0
FOR I ← 1 TO 5
Total ← Total + I
NEXT I
OUTPUT Total
一行里既有文字又有数字
print里的逗号会在各部分之间加一个空格。print("7 x", 1, "=", 7 * 1)打印7 x 1 = 7。+不能把数字和文字连在一起。用逗号,或者先用str把数字变成文字。
常见错误
range(n)数0到n - 1,不是1到n。range(a, b)在b之前停止。- 循环体必须缩进在
for那行下面。
现在轮到你
- 在每个任务中使用
for循环搭配range(...)。 - 按检查答案来测试你的代码。
A counting loop, pass by pass
A for loop repeats its body; watch the counter and the 累加总和.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Use a for loop to print the numbers 1 到 5, each on its own line.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Use a loop and an accumulator to add up every whole number from 1 到 100. Store the total in total.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Multiply together every whole number from 1 到 5 (that is 1×2×3×4×5). Start product at 1 and store the result there.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Print exactly one line: 7 x 1 = 7. Finish the print that is already started. A comma between the parts prints them with spaces: print("7 x", 1, "=", 7 * 1).
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Use a for loop to print the first five lines of the 7 times table: 7 x 1 = 7, 7 x 2 = 14, up to 7 x 5 = 35. The print from the last task is already inside the loop — change the 1 into the loop variable.
点击“运行”查看此处输出。