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

An If Inside an If

Now the path turns both left and right, at different places on each map. In the Which Way at the Corner? exercise, there was only one corner, so the dog decided just once. Here, it has to decide on every tile, in two steps:

  1. Is there a path ahead? If there is, it moves forward.
  2. If not: is there a path to the left? If there is, it turns left, and otherwise right.

The second decision is made only when the first one came out "no". That's why it belongs in the else part of the first block. An If put inside another If is called a nested condition:

  • If path ahead
    • Move forward
  • else
    • If path to the left
      • Turn left ↺
    • else
      • Turn right ↻

What if you put the second If … else under the first one instead of into its else part? Then the dog would also ask about the left after every step on a straight part, where there's no path to the left. So it would turn right, to face the grass, and on the next pass, turn back. It would still get to the goal, but it would take almost twice as long. The else makes sure that the dog turns only when it can't go on.

Instructions

  1. 1

    Get the dog to the goal on all three maps.

Back

5/9

  1. 1. The If Block
  2. 2. If, Else
  3. 3. Which Way at the Corner?
  4. 4. Quiz: One Part per Pass
  5. 5. An If Inside an If
  6. 6. A Path with Bones
  7. 7. Quiz: A Bug in a Nested If
  8. 8. Side Trips
  9. 9. Summary
Next

Try it yourself

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