CoursesAIMathCodePhysicsAbout and FAQ

TwiddleLab / Code / How a Programmer Thinks

Loops: Do It Again

Lesson 5 of 10 · 7 min · Free, no account needed

What you will learn

  • A for loop runs its indented body once for every value: each round is an iteration.
  • range(5) gives 0, 1, 2, 3, 4: it starts at 0 and stops before 5.
  • range(start, stop, step): range(2, 11, 2) gives 2, 4, 6, 8, 10.
  • Change one number and the loop does ten times the work.

Start the lesson

How the lesson goes

  1. Print the numbers from 1 to 100.

    Would you type 100 lines? Tap to type them, one at a time.

  2. Each step is one value of i. Where does i light up last?

    Read the loop, then tap a step.

  3. Run the loop and watch i climb.

    Press Step. The body runs once for every step.

  4. The parts of a loop have names.

    A for loop repeats. The indented lines under it are the body.

    Each round of the body is an iteration. The loop variable i holds a new value every round.

    range(5) makes 0, 1, 2, 3, 4. range(1, 6) starts at 1 and stops before 6, so this loop prints 1 to 5. And range(1, 101) prints 1 to 100.

  5. Make it print 2, 4, 6, 8, 10.

    range can take a start, a stop and a step. Turn the three numbers.

  6. Add up 1 to 5. Be the machine.

    Every round, drag the new value of total into its box. Then press Check.

  7. Pattern painter: paint the dashed stairs.

    Up to 4 blocks in the loop. Set how many times it repeats. Paint exactly the pattern.

  8. AI learns in a loop too. Build its training loop.

    Put the stations in order. The last one sends it back for another round.

  9. This should print 1 to 10. It stops at 9.

    Tap the number that's off, fix it, then Run.

  10. Your loop, ten times bigger.

    Change how many times it repeats, then Run.

Previous lesson: Bugs Are Clues · Next lesson: Lists: Many Boxes in a Row · Part of the course: How a Programmer Thinks

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

Loading TwiddleLab