Appendix A
Exercise 4 solution
The get_omelet_ingredient from make_omelet_q3 could be changed to look like the following:
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”: ingredients[“cheddar”] = 2
elif omelet_name == “western”: ingredients[“jack_cheese”] = 2
ingredients[“ham”] |
= 1 |
ingredients[“pepper”] |
= 1 |
ingredients[“onion”] |
= 1 |
elif omelet_name == “greek”: |
|
ingredients[“feta_cheese”] = 2 |
ingredients[“spinach”] |
= 2 |
# Part 5
elif omelet_name == “mozerella”: ingredients[“mozerella cheese”] = 2 ingredients[“roast red pepper”] = 2 ingredients[“mushrooms”] = 1
# Question 4 - we don’ want anyone hurt in our kitchen! elif omelet_name == “salmonella”:
raise TypeError, “We run a clean kitchen, you won’t get this here” else:
print “That’s not on the menu, sorry!” return None
return ingredients
When run, the error raised by trying to get the salmonella omelet will result in the following error:
>>> make_omelet_q3({‘mozzarella cheese’:5, ‘eggs’:5, ‘milk’:4, ‘roast red pepper’:6, ‘mushrooms’:4}, “salmonella”)
Traceback (most recent call last): File “<stdin>”, line 1, in ?
File “ch5.py”, line 209, in make_omelet_q3 omelet_ingredients = get_omelet_ingredients(omelet_type)
File “ch5.py”, line 179, in get_omelet_ingredients
raise TypeError, “We run a clean kitchen, you won’t get this here” TypeError: We run a clean kitchen, you won’t get this here
>>>
You can see from this that the program was run from <stdin>, which means it was run interactively, with python -i ch5.py or by using codeEditor’s Run with Interpreter option. The function make_ omelet_q3 was called, and the function get_omelet_ingredients was called on line 209 in ch5.py. Python shows you the actual line that was run, in case you needed more information at first glance. Note that depending on the contents of your ch5.py file, the exact line numbers shown in your stack trace will be different from those shown here.
You can next see that line 179 is where get_omelet_ingredients raised the error (though it may be at a different line in your own file).