CoursesAIMathCodePhysicsAbout and FAQ

TwiddleLab / Code / Build with Python

While: Until It's Done

Lesson 3 of 12 · 7 min · Free, no account needed

What you will learn

  • A while loop repeats its body as long as its condition is True.
  • The condition is checked before every lap, even the first: if it starts False, the body never runs.
  • Something in the body must change the condition, or you get an infinite loop.
  • Use for when you know how many times; use while when you repeat until something happens.

Start the lesson

How the lesson goes

  1. Double your coins until you have 100. How many doublings?

    The loop doesn't know in advance. Place your pin: how many laps will the runner do?

  2. Run it. Watch the gate before every lap.

    The condition is checked each time the runner comes round.

  3. Now break it on purpose.

    Tap the line inside the loop to take it out, then Run. Then put it back.

  4. while: repeat until it's done.

    A while loop runs its indented body again and again while its condition is True.

    The condition is checked before every lap. When it's False, Python skips to the first line after the loop.

    An infinite loop never ends: nothing in the body changes the condition. Always ask: what moves us toward False?

  5. Saving for a 1000-coin skin. Make it take exactly 6 weeks.

    Move the sliders: how much you start with and how much you add each week.

  6. Build a password door that keeps asking until it's right.

    Put the lines in order. The test types cat, then dog, then fox42.

  7. Two ways to save a million, starting from 1000. Who gets there first?

    Tap the runner you'd bet on, then Run both.

  8. Lap streak: how many laps before each run?

    Five loops. Tap your answer, then watch. Get 4 to win.

  9. Roll a die until you get a 6. Which loop fits?

  10. A friend tries your door.

    Play the friend: type guesses until it opens.

Previous lesson: Text Tricks · Next lesson: And, Or, Not · Part of the course: Build with Python

Lessons are interactive and need JavaScript. Turn it on to play them.

Loading TwiddleLab