0

Loops inside programs

  1. move right
    repeat 3 times
    move down
    collect the star

    Before, during, after

    A loop can sit in the middle of a program. The robot still reads from the top. Lines before the loop run first. Then the loop runs. Then the lines after it.

  2. move_down()
    repeat 4:
        move_right()

    Count every move

    Line 1 moves the robot down 1. The loop moves it right 4 times. 1 + 4 = 5 moves in all.

  3. move down
    repeat 4 times
    move right

    Watch the robot

    Here is that program as blocks. Tap Run the program. Down 1, then right 4. The robot lands on the flag.

  4. move_up()
    repeat 2:
        move_right()
        move_right()
    say("Done")

    Two lines inside

    A loop can hold more than one line. Both indented lines repeat. Two rights, 2 times, makes 4 moves right. say("Done") is not indented, so it runs once.

  5. move_up()
    repeat 3:
        move_right()

    Make it shorter

    Three move_right() lines in a row can become one loop. Keep move_up() before the loop. The loop gets the number 3.

For parents

Goal: Your child learns to read programs with lines before and after a loop, in the right order.

  • Ask: which lines are inside the loop? Which lines run only once?
  • Count the moves together: the moves before, plus the loop moves, plus the moves after.
  • In the labs your child guesses where a program ends and builds programs with lines before and after a loop.

Away from the screen: Play a game: stand up, then repeat 3: hop, then sit down. Ask your child which part repeated and which parts happened once.

Coding · Loops
Back to top