Looping on a Condition

A for loop walks a collection. You know how many passes there will be before it starts.

A while loop repeats as long as a condition stays true. You don't know the count in advance: keep asking until they enter a valid answer, keep withdrawing until the balance runs out, keep playing until someone wins.

While loops

PYTHON

count = 0
while count < 3:
    print(count)
    count += 1

JAVASCRIPT

let count = 0;
while (count < 3) {
  console.log(count);
  count += 1;
}
Compare → Nearly identical. Python needs the colon and indentation; JavaScript needs parentheses around the condition and braces around the body. The three-part structure is the same: initialize before, test each pass, change inside.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Each pass checks the condition again: 0<3, 1<3, 2<3, then 3<3 is false and the loop exits. Change it so it prints 1 through 5, then change it again so it prints only the even numbers up to 10.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: The Infinite Loop, and How to Avoid It →
← Back