user7978992
user7978992

Reputation:

Python function calling logics

Sorry if this is a dumb question. I have just started learning Python. I agree the below snippet does not work before the definition is not written before calling it.

repeat()

def print_lyrics():
    print('hi')
    print('hello')

def repeat():
    print_lyrics()
    print_lyrics()

However, if i change the order of print_lyrics() and repeat(), it still works.

 def repeat():
    print_lyrics()
    print_lyrics()

 def print_lyrics():
    print('hi')
    print('hello')

 repeat()

Does it not expect us to be in order same as above since repeat() calls print_lyrics(). I m just trying to understand how this works (or) scans this internally(during run time?)

Upvotes: 0

Views: 31

Answers (1)

Tom Karzes
Tom Karzes

Reputation: 24052

It doesn't matter what order you define a set of functions in, as long as all of the functions that are called have been defined before they are called.

In your example, no function calls are executed at the time the functions are defined. It isn't until the invocation of repeat() that the first function call is actually made. At that time, repeat must be defined, as well as all of the functions that it calls, either directly or indirectly.

Upvotes: 1

Related Questions