Chuyển đến nội dung chính
eLearner.app
Mô-đun 2 · Bài học 2 trong tổng số 46/36 trong khóa học~8 min
Bài học theo mô-đun (2/4)

vòng lặp while

The while loop repeats a block as long as a condition stays true. Use while when you don't know up front how many iterations you'll need: the number of rounds depends on something that changes inside the loop.

Syntax

Python
n = 1
while n < 1000:
    n = n * 2
n  # 1024

The indented block is executed repeatedly. Before each iteration Python evaluates the condition: as soon as it becomes false, the loop terminates and execution continues after the block.

Common patterns

Manual counter — equivalent to a classic for in other languages:

Python
i = 0
while i < 5:
    print(i)
    i = i + 1

Infinite loop + internal exit condition — useful when the condition is evaluated after doing something:

Python
acc = 0
while True:
    acc = acc + 1
    if acc * acc > 100:
        break
acc  # 11   (11*11 = 121 is the first square > 100)

break exits immediately from the innermost loop (we'll see it in the next lesson).

The classic mistake: the infinite loop

If the variable in the condition does not change inside the loop, the program never terminates. It is the number-one bug with while:

Python
n = 0
while n < 10:
    print(n)   # n is never modified → infinite loop!

In our exercises there is an execution timeout, so an infinite loop will fail with a clear message instead of freezing the browser. But in production an infinite loop is a serious bug.

Infinite loops risk and termination conditions

A while loop executes as long as its condition evaluates to True. If you forget to update the variables that affect the condition, your loop will run infinitely, freezing the runtime. Always ensure that the loop body makes progress towards the exit condition.

Try it yourself

tập thể dục#python.m2.l2.e1
Nỗ lực: 0Đang tải…

Find the smallest integer `n >= 1` such that 2**n exceeds one million. Assign it to `result` and evaluate it (it should be 20).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

2**20 = 1,048,576 is the first to exceed 1,000,000.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#python.m2.l2.e2
Nỗ lực: 0Đang tải…

Starting from `n = 1000`, halve n with integer division (n // 2) until it becomes 0. Count how many iterations it takes in `steps`. Evaluate `steps`.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

1000 → 500 → 250 → 125 → 62 → 31 → 15 → 7 → 3 → 1 → 0: ten steps.

Giải pháp khả dụng sau 3 lần thử

Additional challenge

tập thể dục#python.m2.l2.e3
Nỗ lực: 0Đang tải…

Given the variable `n = 32`, write a `while` loop to count how many times you can divide `n` by 2 (using floor division `//`) before `n` becomes less than or equal to 1. Store the count in `divisions` and evaluate it.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

The while condition is n > 1. Inside the loop, divide n by 2 and increment divisions by 1.

Giải pháp khả dụng sau 3 lần thử