Skip to content
BENIBIX Learn

For Loop vs While Loop

A for loop goes over a list and stops when the list runs out. A while loop goes on until its test turns false.

Development🧩 Programming Concepts

For Loop

A loop that runs once for each item in a list, then stops by itself.

A for loop runs its lines once for each item in a list or a range. Each time round, a variable holds the next item. When the items run out, the loop ends by itself. Python writes it as for name in names. Other languages, like C and JavaScript, often count with a number instead.

Example
A class app runs a for loop over 28 names. It sends each pupil the same reminder about the school trip.
Why it matters
Most loops go over a list of things. A for loop does that and can never forget to stop.
Full entry
Development🧩 Programming Concepts

While Loop

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

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
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.
Full entry

In one line

For Loop
A loop that runs once for each item in a list, then stops by itself.
While Loop
A loop that keeps going while a test is true, and stops when it turns false.