0

Repeat in code

  1. move_right()
    move_right()
    move_right()
    move_right()

    The same line again and again

    The star is at the end of a long hall. The robot needs move_right() 4 times. Typing the same line again and again is slow.

  2. repeat 4:
        move_right()

    A loop does it for you

    A repeat in code is called a loop. Write repeat, a number and a colon. Put the step on the next line. This loop moves right 4 times.

  3. repeat 4:
    how many times
    move_right()
    indented, so inside

    The indent

    See the spaces before move_right()? That push in is called an indent. Indented lines are inside the loop. They run every time the loop goes round.

  4. repeat 4 times
    move right

    Watch the robot

    Here is the loop as blocks on a board. Tap Run the program. The robot moves right 4 times and reaches the star. Same moves, much less typing.

  5. repeat 3:
        move_right()
    say("Done")

    Inside or outside

    Only indented lines repeat. Here move_right() runs 3 times. say("Done") is not indented. It runs once, after the loop ends.

For parents

Goal: Your child learns to read and write a repeat loop in code, and to tell which lines are inside it.

  • Ask: which line is inside the loop? How can you tell?
  • When you see the same line many times, ask how a loop could make it shorter.
  • In the labs your child builds loops and guesses where a loop takes the robot. Tap See it as code to see the indent.

Away from the screen: Say "repeat 3: clap" and your child claps 3 times. Then try "repeat 4: jump", and add "say Done" at the end.

Coding · Loops
Back to top