Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write three small functions square(n), double(n) and negate(n), and a dictionary operations that maps the words "square", "double" and "negate" to them. Then write a loop that applies the operations named in a list of words to the number 5, and shows the results. What happens for a word that is not in the dictionary?
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Store the functions themselves in the dictionary, with no brackets. Look up the word, and call the function with the number.
Check. The results are 25, 10 and -5. The word cube is not a key, so the else part says that it is unknown. Without the if, operations["cube"] would be a KeyError.
Answer: square -> 25, double -> 10, negate -> -5, and cube -> unknown operation.
Log in to join the discussion.
Loading…