1

I'm currently working through Head First Python and I'm beginning to work on defining functions. The goal of this below program is to create a function print_lol() where it takes one argument: a list to display on the screen. The final code that works is as follows:

def print_lol(the_list):
    for each_item in the_list:
        if isinstance(each_item,list):
            print_lol(each_item)
        else:
            print(each_item)

So if we put in a list like:

movies=["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91, ["Graham Chapman", ["Michael Palin", "John Cleese", "Terr Gilliam", "Eric Idle", "Terry Jones"]]]

the will just output all the entries in this array.

My question is, why does print_lol(each_item) in the fourth line work? I understand that the logic is that the program will look at each item and if its not in a list it will just print the item but if it is how does the computer know what print_lol is? I don't think the first line adequately explains print_lol either. Is print_lol a command that comes with Python 3?

Johan
  • 3,577
  • 1
  • 14
  • 28
cambelot
  • 165
  • 8
  • Search the defintion of a recursive function in programming ( it is one that calls itself ) – rachid el kedmiri Oct 07 '18 at 22:21
  • When a script is executed first, the `def` and following is a command to define (but not execute) a function. The function is then entered with name `print_lol` in a global namespace. When the function is called later, the definition is readily available. – Michael Butscher Oct 07 '18 at 22:22

2 Answers2

1

You declare a function on line 1 that you choose to call print_lol, and on line 4 you recursively call it from within itself. print_lol isn't a command that comes in python, it's literally a function that you declare in the code you provided.

Very simplified, think of the function print_lol like it takes off one layer of list for each recursive call it does until it's not a list anymore, but just strings left. Then it prints those strings.

Johan
  • 3,577
  • 1
  • 14
  • 28
1

In python, it resolves names at run time.

You can write a function like this

def f():
    return k()

The code is fine, but k must exist at run time when the function is executed.

What happens is that "def f" inserts an entry called f in the list of global symbols, so when at run time f() is found, the global symbols are searched for "f", which in your example will be there, because it had been previously defined.

LtWorf
  • 7,286
  • 6
  • 31
  • 45