Iteration — loops
Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
English
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):.

English
for i in range(5):
print("Hello")
English
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.
English
for n in range(1, 6):
print(n)
English
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.

English
count = 0
while count < 5:
print(count)
count = count + 1
English
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.
English
total = 0
while True:
total = total + 1
if total >= 3:
break
print(total)
Khám phá
Each pass changes count
A loop repeats its body; count must change so the test finally fails.
English
In the exam: FOR, WHILE, REPEAT
- Pseudocode has all three loop types.
FOR I ← 1 TO 5
OUTPUT I
NEXT I
English
Common mistakes
- A
forloop repeats a known number of times; awhilerepeats until something changes. range(n)runs0ton - 1.- Ensure a
whileloop can end: make its condition become false or usebreak.
English
Now you try
- Pick the loop that fits each task.
- Press Check answer to test your code.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Use a for loop to print the numbers 1 đến 5, one on each line.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Use a loop to add up the numbers 1 đến 10, then print the total (it is 55).
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Read a whole number n, then count xuống from n đến 1, one per line. For input 3, print 3, 2, 1.
Nhấn Chạy để xem kết quả ở đây.