Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

A Loop in a Function

The dog is in a hedge maze with a single winding path. The path turns five times, the same way on all three maps: right, left, left, right and right. But the straight parts between the turns have different lengths on every map, so you can't count the steps.

You know how to walk a straight part of any length: Repeat while path ahead with Move forward inside. The dog needs that six times, once for every straight part. Put it into a function:

  • Define walkToHedge
    • Repeat while path ahead
      • Move forward

A function can hold any blocks, a loop too. Each call then runs the whole loop: the dog walks until there's a hedge in front of it, however far away that is. The same call takes four steps in one place and one step in another. So a function doesn't have to make the same moves every time. This one does what each straight part needs.

Between the calls come the turns. They don't make a regular pattern, so no loop fits the whole way. And the dog can't find out by itself which way to turn: there are no conditions for left and right among the blocks this time. You tell it where to turn, and the function finds out how far to walk.

Instructions

  1. 1

    Get the dog to the goal on all three maps.

  2. 2

    Use at most 15 blocks.

Back

3/9

  1. 1. Teach the Dog a Trick
  2. 2. A Function in a Loop
  3. 3. A Loop in a Function
  4. 4. Quiz: Calling a Function
  5. 5. Two Functions
  6. 6. A Function That Searches
  7. 7. Fix the Function
  8. 8. Quiz: A Bug in a Function
  9. 9. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.