Skip to content
BENIBIX Learn

While Loop

Development🧩 Programming ConceptsControl Flow

Also known as while

A loop that keeps going while a test is true, and stops when it turns false.

Think of it like

Think of it like stirring soup while it is still lumpy. You stop the moment it is smooth.

Example

A rocket game counts down with a while loop. It prints 3, 2, 1, then the test n > 0 turns false and it prints Go!

Why it matters

Some jobs have no fixed count, like wait until the file is ready. A while loop fits those.

Definition

A while loop keeps running as long as a test stays true. It checks the test before every pass. When the test turns false, the loop stops. You use it when you do not know ahead of time how many passes you need. Something inside the loop must change the answer, or it never ends.

Example code

python
n = 3
while n > 0:
    print(n)
    n = n - 1
print("Go!")
It prints 3, 2 and 1, then Go! once n reaches 0.

Common mistake

Forgetting to change anything inside the loop. The test stays true and the program hangs.

Key takeaways

  1. 1
    Test before each pass. It checks, then runs, then checks again.
  2. 2
    Unknown count. Use it when you cannot count passes ahead.
  3. 3
    Change the test. Something inside must move it toward false.

Compare

Learn it properly