Exercise 25

Dictionaries and Functions

In this exercise, we’re going to do something fun by combining functions with dicts. The purpose of this exercise is to confirm that you can combine different things in Python. Combination is a key aspect of programming, and you’ll find that many “complex” concepts are nothing more than a combination of simpler concepts.

Step 1: Function Names Are Variables

To prepare we first have to confirm that a function’s name is just like other variables. Take a look at this code:

1   def print_number(x):
2       print("NUMBER IS", x)
3
4   rename_print = print_number
5   rename_print(100)
6   print_number(100)

If you run this code, you’ll see that rename_print does the exact same thing as print_number ...

Get Learn Python the Hard Way: A Deceptively Simple Introduction to the Terrifyingly Beautiful World of Computers and Data Science, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.