Stage 1 · 30 minutes · Free
for and while loops
Repeat work with for and range(), while, accumulation, break and continue.
Objectives
- Use for with range(start, stop, step)
- Use while with a stopping condition
- Write accumulation patterns
- Use break and continue
Why learn this
Computers are best at doing the same thing again and again without getting tired. Printing 100 lines, adding 1000 numbers, going through a class list: all of it needs loops.
Concept
for i in range(n): repeats n times with i = 0, 1, ..., n-1. range(a, b) goes from a to b-1. range(a, b, buoc) steps by buoc.
while dieu_kien: repeats while the condition stays true. You must have a statement that gradually makes the condition false, otherwise it loops forever (the grader stops after a few seconds).
Accumulation pattern: create tong = 0 before the loop, each round tong = tong + gia_tri.
break exits the loop immediately; continue skips the rest of the current round.
Syntax
for i in range(1, 6):
print(i)
while n > 0:
n = n - 1
Example
n = int(input())
tong = 0
for i in range(1, n + 1):
tong = tong + i
print("Tổng 1 đến", n, "là", tong)Input data:
5
Output:
Tổng 1 đến 5 là 15
Line-by-line walkthrough
- Line 1: n = 5.
- Line 2: tong starts at 0.
- Line 3: i runs 1, 2, 3, 4, 5 (range stops before n + 1 = 6).
- Line 4: each round adds i to tong: 1, 3, 6, 10, 15.
- Line 5: printed after the loop (this line is NOT indented).
Common mistakes
for i in range(1, 5): # muốn 1..5range stops before the last number, giving only 1..4.
range(1, 6) hoặc range(1, n + 1)while i < 5:
print(i)i never increases, so it loops forever.
Thêm i = i + 1 trong vòng lặp.for i in range(5):
tong = 0
tong = tong + iPutting tong = 0 inside the loop wipes the total every round.
Đặt tong = 0 trước vòng for.Summary
- for + range to repeat a known number of times.
- while repeats by condition; remember to make the condition gradually false.
- An accumulation variable is initialized before the loop.
- break exits, continue skips the current round.
Write code right in the browser; the grader runs real Python and points to the exact wrong line.
Practice free