Advanced Python Development Course
Chapter
>
Level
Advanced Functions
Nested Functions
Objective
Collect, redistribute and put away cloth produced by the machines by using nested functions.
Sometimes you’ll want to place functions inside other functions in order to expand that function’s capabilities. These are called Nested functions or Inner functions, they have various uses, from creating simple reusable code inside a function, to protecting your functions from external manipulation.
Inside workshop there are several cloth making machines, some have cloth that is ready for storage, others require thread in order to finish producing the cloth. Each one has either a"red" or "green" or green carpet in front of it which will outline how it is used. In the code editor a Function will be written that will let us operate the machine and either collect or place materials from the machine.
def operate_machine(color):
def collect_cloth():
# Collect Code
player.speak("Cloth is ready for storage")
def place_thread():
# Place Code
player.speak("Machine needed more materials")
if color == "green":
collect_cloth()
if color == "red":
place_thread()
The function is named operate_machine and takes an argument named color . Depending on what color carpet the machine is in front of, entering either "red" or "green" as an argument will change the machine’s operation allowing you to either place or collect items.
Inside the function you will find two Nested functions, named collect_cloth() and place_thread() used for the purposes outlined in their names. They are missing lines required to perform their action, on collect_cloth() add the line player.collect("cloth") , which is followed by player.speak("Quilt is ready for storage") and on place_thread() add the line player.place("thread") which is followed by player.speak("Machine needed more materials").
Once the missing lines of code have been added to the Nested functions walk to the light X mark in front of the crate and collect "thread" to be used in the machine, like this player.collect("thread") .
The Walk to the dark X marks inside the workshop and use the custom function operate_machine while facing the machines. Add either "red" or "green" as an argument depending on the color carpet the X mark is located on, for example: operate_machine("red") . This will allow you to place the thread and collect the cloth.
Once you have collected all cloth, walk to the gold X mark next to the crate in the back and use the place() function to store the cloth. Create a variable named cloths, add to it the number of cloths you’ve collected and store it in the crate in order to complete the level, like this: player.place(cloths) .