Head first python

Page 64

reduce, reuse, recycle

Don’t repeat code; create a function Take a look at the code that you’ve created so far, which (in an effort to save you from having your brain explode) has already been amended to process yet another nested list. Notice anything?

This code is essentially the same as this code… for each_item in movies:

…which is essentially the same as this code…

if isinstance(each_item, list): for nested_item in each_item: if isinstance(nested_item, list): for deeper_item in nested_item:

if isinstance(deeper_item, list): for deepest_item in deeper_item: print(deepest_item) else: print(deeper_item) else: print(nested_item) else: print(each_item)

h There’s not mucong these difference am ts, either! four statemen

This code is beginning to get a little scary… Your code now contains a lot of repeated code. It’s also a mess to look at, even though it works with the movie buff ’s amended data. All that nesting of for loops is hard to read, and it’s even harder to ensure that the else suites are associated with the correct if statement. There has to be a better way…but what to do? When code repeats in this way, most programmers look for a way to take the general pattern of the code and turn it into a reusable function. And Python programmers think this way, too. Creating a reusable function lets you invoke the function as needed, as opposed to cutting and pasting existing code. So, let’s turn the repeating code into a function. 28

Chapter 1

…which is not that much different than this code.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.