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)
合計を作る(累加器)
- アクミュレーターはループ内で成長する変数です。
- ループ开始前に
0で初期化してください。 - 各パスで足し算して、累計を作ります。
total = 0
for n in range(1, 6):
total = total + n
print(total)
Cambridge擬似コードにおける表現
- Pythonの
for … rangeループは試験のカウント制御型FOR … NEXTに相当します。
Total ← 0
FOR I ← 1 TO 5
Total ← Total + I
NEXT I
OUTPUT Total
1行に単語と数字
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.
実行ボタンをクリックして出力を確認してください。