Counting loops · カウントループ
Repeat with for
- A
forloop repeats code a fixed number of times. - The body of the loop is indented, like an
if. - A loop variable holds a new value on each pass.
Counting with range
range(5)gives the numbers0, 1, 2, 3, 4(stops before 5).range(1, 6)gives1, 2, 3, 4, 5(start included, stop not).range(0, 10, 2)counts in steps of 2.
for i in range(5):
print(i)
Build a total (accumulator)
- An accumulator is a variable that grows inside a loop.
- Start it at
0before the loop. - Add to it on each pass to build a running total.
total = 0
for n in range(1, 6):
total = total + n
print(total)
In Cambridge pseudocode
- A Python
for … rangeloop is the exam's count-controlledFOR … NEXT.
Total ← 0
FOR I ← 1 TO 5
Total ← Total + I
NEXT I
OUTPUT Total
Words and a number on one line
- A comma inside
printputs a space between the parts. print("7 x", 1, "=", 7 * 1)prints7 x 1 = 7.+cannot join a number to text. Use the comma, or turn the number into text withstr.
Common mistakes
range(n)counts0ton - 1, not1ton.range(a, b)stops beforeb.- The loop body must be indented under the
forline.
Now you try
- Use a
forloop withrange(...)in each task. - Press Check answer to test your code.
A counting loop, pass by pass · カウントループ、段階ごとに
A for loop repeats its body; watch the counter and the running total. · for ループはその本体を繰り返します;カウンタと累積和を見てください。
Use a for loop to print the numbers 1 to 5, each on its own line. · forループを使って、各数字を別々の行に印刷し、1から5までの数字を表示する。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Use a loop and an accumulator to add up every whole number from 1 to 100. Store the total in total. · ループと累加器を使って、1 から 100 までのすべての整数を足し合わせます。合計をtotal に格納してください。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Multiply together every whole number from 1 to 5 (that is 1×2×3×4×5). Start product at 1 and store the result there. · 1 から 5 までのすべての整数を掛け合わせます(つまり 1×2×3×4×5)。product を 1 で始め、結果をそこに格納してください。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
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). · 以下の通りちょうど1行を出力してください:7 x 1 = 7。すでに開始されている print を完了させてください。部分間にコンマを使うとスペースで表示されます:print("7 x", 1, "=", 7 * 1)。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
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. · for ループを使って掛け算の表の7の段の最初の5行を出力してください:7 x 1 = 7、7 x 2 = 14、7 x 5 = 35 まで。先ほどのタスクの print はすでにループ内にあります——ループ変数に 1 を変更してください。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。