Advanced Python Development Course
Chapter
>
Level
Generators
Creating a Generator
Sometimes you may want to generate a values consistently rather than a one time output. Similar to how functions work, generators are written and executed in the same way except they use yield() instead of return() when producing an output.
In this exercise you must fill bottles with milk from the tanks at the stable. Use a generator to iterate filling up the bottles and making sure any surplus milk is collected from the tanks.

Objective
Fill bottles up with milk by pumping the milk tanks using generators.
The machines that store the cow milk are nearly full, you need to bottle the milk and store it before it goes bad. This can be a bit of a tricky task using normal means and the amount of milk you can extract can vary a bit. Thankfully you can use generators to make this process seamless and straightforward.
There are two (2) tanks with milk that need to have their milk pumped and bottled. Each machine has compartments that store milk, these are represented by list constants named: tank_a and tank_b . On top of that, each tank tends to have a surplus left over that you can collect.
Generators follow the same syntax as functions but will use yield instead of return for their output. Set up a generator named fill() and set it with the argument list , this would be where you input the constants mentioned in the above paragraph.
def fill(list):
for x in range(3):
yield list[x]
yield 5
The generator reads the data from the three (3) fields in the list constants, represented by the compartments in the machine, and adds a surplus at the end which is five (5).
Collect the basket object in the field to gain access to the bottles necessary for filling and walk to the the two (2) X marks to collect the milk using a for loop.
Thanks to the yield statement the values produced from the generator can be read directly from a for loop as well. Set one up that uses the collect() function to acquire the "milk" from the machine. Follow that up by using speak() to check how much milk each bottle has stored. For example:
for bottles in fill(tank_a): player.collect("milk") player.speak("%d pints of milk collected" % (bottles))
Write and use this for loop on both X marks, on the light X mark use the argument tank_a and on the dark X mark use the argument tank_b in order to complete the level.