Page 92 -
P. 92
using range
Now that you know a bit about the range() BIF, you were to amend your function to use
range() to indent any nested lists a specific number of tab-stops.
Hint: To display a TAB character on screen using the print() BIF yet avoid taking a new-line
(which is print()’s default behavior), use this Python code: print("\t", end='').
"""This is the "nester.py" module and it provides one function called print_lol()
which prints lists that may or may not include nested lists."""
level
def print_lol(the_list, ):
"""This function takes a positional argument called "the_list", which
is any Python list (of - possibly - nested lists). Each data item in the
provided list is (recursively) printed to the screen on it's own line."""
A second argument called “level" is used to insert tab-stops when a nested list is encountered."""
for each_item in the_list:
if isinstance(each_item, list): Use the value of “level” to control
print_lol(each_item) how many tab-stops are used.
else:
for tab_stop in range(level):
print("\t", end='') Display a TAB character for each level
print(each_item) of indentation.
It’s time to test the new version of your function. Load your module file into IDLE, press F5 to import the function
into IDLE’s namespace, and then invoke the function on your movies list with a second argument:
Invoke your function, being sure to provide
>>> print_lol(movies, 0) a second argument.
The Holy Grail
The data in “movies” starts to appear on screen…
1975
Terry Jones & Terry Gilliam
91
Traceback (most recent call last): …then all hell breaks loose! Something is not right here.
File "<pyshell#2>", line 1, in <module>
print_lol(movies,0)
File "/Users/barryp/HeadFirstPython/chapter2/nester/nester.py", line 14, in print_lol
print_lol(each_item) Here’s your clue as to
TypeError: print_lol() takes exactly 2 positional arguments (1 given) what’s gone wrong.
Your code has a TypeError, which
56 Chapter 2 caused it to crash.