Iteration — loops · 反復 — ループ
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
Count-controlled loops
- Iteration means repeating steps.
- A count-controlled loop repeats a fixed number of times.
- In Python that is
for i in range(n):.
for i in range(5):
print("Hello")
Choosing the range
range(5)gives0, 1, 2, 3, 4.range(1, 6)gives1, 2, 3, 4, 5— it stops before 6.range(2, 11, 2)counts in steps of 2.
for n in range(1, 6):
print(n)
Pre-condition loops: while
- A pre-condition loop tests before each pass.
- It may run zero times if the test is false at the start.
count = 0
while count < 5:
print(count)
count = count + 1
Post-condition loops: REPEAT UNTIL
- A post-condition loop tests after each pass, so it always runs at least once.
- Python has no
repeat, so we usewhile Truewithbreak.
total = 0
while True:
total = total + 1
if total >= 3:
break
print(total)
Explore · 探索
Each pass changes count · 各パスでcountが変化する
A loop repeats its body; count must change so the test finally fails. · ループは本体を繰り返します;countが変化することで最終的にテストが失敗する必要があります。
In the exam: FOR, WHILE, REPEAT
- Pseudocode has all three loop types.
FOR I ← 1 TO 5
OUTPUT I
NEXT I
Common mistakes
- A
forloop repeats a known number of times; awhilerepeats until something changes. range(n)runs0ton - 1.- Change the condition inside a
while, or it never ends.
Now you try
- Pick the loop that fits each task.
- Press Check answer to test your code.
Use a for loop to print the numbers 1 to 5, one on each line. · forループを使用して、1から5までの数字を出力してください。各行に1つずつ。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Use a loop to add up the numbers 1 to 10, then print the total (it is 55). · ループを使って1から10までの数値を合計し、総計(結果は55)を出力します。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Read a whole number n, then count down from n to 1, one per line. For input 3, print 3, 2, 1. · 整数nを入力として読み込み、nから1まで逆順にカウントし、1行ごとに出力します。入力3に対しては、3、2、1を出力します。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。