Teacher's Guide

Chapter 1 / Level 1: Creating a Generator

Teaching Objective:

  • Student understands a generator’s syntax
  • Learns practical uses for generators
  • Learns how they differ from lists and functions

Guide

In this exercise you must use a generator in order to pump milk from two of the tanks in the stable. Generators are similar to custom functions in how they are written but use yield instead of return to produce their output. This allows them to consistently generate output rather than have them return a single result.

First thing you need to do is set up a generator named fill() that takes an argument named list . The reason it takes the argument list is because there are two list constants named tank_a and tank_b that hold the amount of milk stored in the tanks. In this exercise you will use these two lists in conjunction with fill() in order to pump milk from the tanks into bottles. The generator will also drain any surplus milk the tanks have, thus why it has two yield statements.

def fill(list):
  for x in range(3):
    yield list[x]
    
  yield 5

Grab the basket located next to the grain sign in order acquire the bottles needed to collect the milk from the tanks. Once that is done head for the X marks and use the provided for loop that uses the generator to pump the milk.

for bottles in fill(tank_a):
  player.collect("milk")
  player.speak("%d pints of milk collected" % (bottles))

........

for bottles in fill(tank_b):
  player.collect("milk")
  player.speak("%d pints of milk collected" % (bottles))

The collect() function needs to be added in order to acquire "milk" . Use the tank_a constant with the generator when standing on the light X mark and tank_b when standing on the dark X mark in order to complete the level.

Map overview and path

Map overview and path

Code Solution

import player

def fill(list):
  for x in range(3):
    yield list[x]
    
  yield 5
  
player.turn_left()
player.move_forward(8)
player.turn_left()
player.move_forward(2)
  
for bottles in fill(tank_a):
  player.collect("milk")
  player.speak("%d pints of milk collected" % (bottles))

player.turn_left()
player.move_forward(6)
player.turn_right()

for bottles in fill(tank_b):
  player.collect("milk")
  player.speak("%d pints of milk collected" % (bottles))
Chapter 1 / Level 1: Creating a Generator | Teacher's Guide