Teacher's Guide

Chapter 7 / Level 3: Passing functions as arguments

Teaching Objective:

  • Student understand how to use a function as an argument for another function
  • Understands how to consolidate code in a more readable form
  • Understands how functions can be used to optimize code and make it more compact

Guide

In this exercise, walk to each X mark and count the number of items in the field using the return value of custom functions. There are three items total on the field: "Red Mandrake", "Blue Mandrake" and "Poison Mushroom" .

def name_and_number(name, number):
	return( "There are %d %ss in the field." % (number, name))

......

player.speak(name_and_number("Red Mandrake", 4))

......

player.speak(name_and_number("Blue Mandrake", 6))

......

player.speak(name_and_number("Poison Mushroom", 5))

......

On the last X mark, add the numbers for each of the items using another custom function to complete the level.

def add_numbers(num1, num2, num3):
	return(num1 + num2 + num3)

......

player.speak(add_numbers(4, 6, 5))

Map overview and path

Map overview and path

Code Solution

import player
def name_and_number(name,number):
	return( "There are %d %ss in the field." % (number, name))
player.turn_left()
player.move_forward(2)
player.turn_left()
player.speak(name_and_number("Red Mandrake", 4))
player.turn_right()
player.move_forward(2)
player.turn_left()
player.speak(name_and_number("Blue Mandrake", 6))
player.turn_right()
player.move_forward(2)
player.turn_left()
player.speak(name_and_number("Poison Mushroom", 3))
player.turn_right()
player.move_forward(2)
player.turn_left()
player.move_forward(5)	
def add_numbers(num1, num2, num3):
	return(num1 + num2 + num3)	
player.speak(add_numbers(4, 6, 3))
Chapter 7 / Level 3: Passing functions as arguments | Teacher's Guide