Teacher's Guide

Chapter 7 / Level 5: Using Conditions in Functions

Teaching Objective:

  • Student learns how to put together complex, multi faceted functions
  • Understands how consolidating various functions into a single function and sorting them with conditions can be used to optimize code
  • Learns how to use conditions in a way where a function can perform completely different sets of actions.

Guide

In this exercise, the student must create a custom function to move through the swamp’s gates and build bridges. This custom function must have conditions in order to work for both tasks.

Name the custom function navigate_swamp and set it up so it takes a string argument outlining if you want to run code to either “open” or “build”. Set up if statements inside the function to execute either condition.

def navigate_swamp(action):
  if action == "build":
    player.build("bridge")
    player.move_forward()
    player.build("bridge")
    player.move_forward()
    player.build("bridge")
    player.move_forward()

  if action == "open":
    player.open()
    player.move_forward(2)
    player.turn_left()
    player.turn_left()
    player.colse()
    player.turn_left()
    player.turn_left()

Have the “build” condition use the the build() function in combination with move forward, and repeat the code three times so you may clear the bridge in the middle of the map. Set the “open” condition to use the open() and close() functions in a way where you open the gate, move across, turn around and close it.

Use the custom function to navigate the map, be sure to pick up all the logs in the field before building the bridge. once you use the functions to clear the obstacles head for the exit marked by a star and clear the map.

Map overview and path

Map overview and path

Code Solution

import player

def navigate_swamp(action):   
  if action == "build":
    player.build("bridge")
    player.move_forward()
    player.build("bridge")
    player.move_forward()
    player.build("bridge")
    player.move_forward()
    
  if action == "open":
    player.open()
    player.move_forward(2)
    player.turn_left()
    player.turn_left()
    player.close()
    player.turn_left()
    player.turn_left()
    
player.turn_left()
player.turn_left()
player.move_forward(2)
navigate_swamp("open")
player.move_forward(7)
player.turn_right()
player.move_forward(3)
player.turn_right()
player.move_forward(2)
player.turn_right()
player.move_forward()
player.turn_left()
player.move_forward(3)
player.turn_left()
player.move_forward()
navigate_swamp("build")
player.move_forward(4)
player.turn_left()
player.move_forward()
navigate_swamp("open")
player.move_forward()
Chapter 7 / Level 5: Using Conditions in Functions | Teacher's Guide