|
| 1 | +# recipes.py |
| 2 | +# |
| 3 | +# This module demonstrate the concept of encapsulation within a Python module. |
| 4 | + |
| 5 | +def new(name, num_servings): |
| 6 | + """ Create and return a new recipe. |
| 7 | + """ |
| 8 | + return {'name' : name, |
| 9 | + 'num_servings' : num_servings, |
| 10 | + 'instructions' : [], |
| 11 | + 'ingredients' : []} |
| 12 | + |
| 13 | + |
| 14 | +def add_instruction(recipe, instruction): |
| 15 | + """ Add an instruction to the recipe. |
| 16 | + """ |
| 17 | + recipe['instructions'].append(instruction) |
| 18 | + |
| 19 | + |
| 20 | +def add_ingredient(recipe, ingredient, amount, units): |
| 21 | + """ Add an ingredient to the recipe. |
| 22 | + """ |
| 23 | + recipe['ingredients'].append({'ingredient' : ingredient, |
| 24 | + 'amount' : amount, |
| 25 | + 'units' : units}) |
| 26 | + |
| 27 | + |
| 28 | +def get_name(recipe): |
| 29 | + return recipe['name'] |
| 30 | + |
| 31 | + |
| 32 | +def get_num_servings(recipe): |
| 33 | + return recipe['num_servings'] |
| 34 | + |
| 35 | + |
| 36 | +def get_instructions(recipe): |
| 37 | + return recipe['instructions'] |
| 38 | + |
| 39 | + |
| 40 | +def get_ingredients(recipe): |
| 41 | + return recipe['ingredients'] |
| 42 | + |
| 43 | + |
| 44 | +def to_string(recipe, num_servings): |
| 45 | + """ Return a list of strings with a description of this recipe. |
| 46 | +
|
| 47 | + The recipe will be customized for the given number of servings. |
| 48 | + """ |
| 49 | + s = [] |
| 50 | + s.append("Recipe for {}, {} servings:".format(recipe['name'], |
| 51 | + num_servings)) |
| 52 | + s.append("") |
| 53 | + s.append("Ingredients:") |
| 54 | + s.append("") |
| 55 | + for ingredient in recipe['ingredients']: |
| 56 | + s.append(" {} - {} {}".format(ingredient['ingredient'], |
| 57 | + ingredient['amount'] * num_servings / |
| 58 | + recipe['num_servings'], |
| 59 | + ingredient['units'])) |
| 60 | + s.append("") |
| 61 | + s.append("Instructions:") |
| 62 | + s.append("") |
| 63 | + for i,instruction in enumerate(recipe['instructions']): |
| 64 | + s.append("{}. {}".format(i+1, instruction)) |
| 65 | + |
| 66 | + return s |
| 67 | + |
0 commit comments