Learn

What if you approached tile-placing another way: you don’t know how many tiles to place, but you know when to stop. How could you communicate this type of command to a computer? Give it the instructions and a condition:

While there are pink tiles available: placeTile('pink') placeTile('orange') placeTile('mint')

This is a while loop, or condition-controlled loop. It repeats a set of instructions while that condition is true. In this case, the computer will place tiles while there are pink tiles available.

In a while loop, the computer checks if the condition is satisfied. If it is, it executes the tasks in the loop body. It checks the condition again, and repeats. This continues until the condition is not satisfied, and it stops executing the tasks.

Use while loops when you know when a program should stop, but not the number of times it should repeat.

Instructions

Try the same task with a while loop:

  • Insert the three instructions (pink, orange, mint)
  • Select a condition
  • Run it

Be careful of infinite loops! If the condition is always true, the loop will never stop.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?