Calling Functions from within Other Functions

Functions declared within the top level, or global scope, can be used from within other functions and from within the functions inside of other functions. The names in the global scope can be used from everywhere, because the most useful functions need to be available for use within other functions.

In order to have a make_omelet function work the way you saw earlier, it should rely on other functions to be available, so they can be used by make_omelet.

This is how it should work: First, a function acts like sort of a cookbook. It will be given a string that names a type of omelet and return a dictionary that contains all of the ingredients and their quantities. This function will be called get_omelet_ingredients, and it needs one parameter — the name of the omelet:

def get_omelet_ingredients(omelet_name):

This contains a dictionary of omelet names that can be produced, and their ingredients

# All of our omelets need eggs and milk ingredients = ("eggs":2, "milk":1} if omelet_name == "cheese":


'cheddar'1] = 2

elif omelet_name

== "western":


' jack_cheese"]

= 2



= 1



= 1



= 1

elif omelet_name

== "greek":

ingredients["feta_cheese"] = 2 ingredients["spinach"] = 2


print("That's not on the menu, sorry!") return None return ingredients

The second function you need to make omelets is a function called make_food that takes two parameters. The first is a list of ingredients needed — exactly what came from the get_omelet_ ingredients function. The second is the name of the food, which should be the type of omelet:

def make_food(ingredients_needed, food_name):

make_food(ingredients_needed, food_name)

Takes the ingredients from ingredients_needed and makes food_name

for ingredient in ingredients_needed.keys(): print("Adding %d of %s to make a %s" % (ingredients_needed[ingredient], ingredient, food_name)) print("Made %s" % food_name) return food_name

At this point, all of the pieces are in place to use the make_omelet function. It needs to call on the get_ omelet_ingredients and the make_food functions to do its job. Each function provides some part of the process of making an omelet. The get_omelet_ingredients function provides the specific instructions for specific kinds of omelets, and the make_food function provides the information needed to know that any kind of food can, if you look at it one way (a very simplistic way for the sake of demonstration!), be represented as the result of just mixing the right quantities of a number of ingredients.

0 0

Post a comment