Mader n fader
Mader n fader

Reputation: 146

Call a function in another one

I have coded a quite simple program but I'll post a script short enough to reach the main point of the question:

def hello():
    print("hello")
    good_morning()

def good_morning():
    print("good morning")
hello()

I've a question about functions. According to a Python guide (written by Allan Downey) Python will execute hello() as if it were in the the first piece of program so how can this work if the call is before the definition of the function?

Upvotes: 1

Views: 52

Answers (3)

Barmar
Barmar

Reputation: 782488

Statements are executed in order. By the time you execute hello() you have executed the statement that defines good_morning. There, when hello() tries to call good_morning(), it succeeds because the function is defined.

In other words, the function has to be defined before the function that uses it is called, not before the function that uses it is defined.

Upvotes: 1

developer_hatch
developer_hatch

Reputation: 16224

As you can see in this editor online https://repl.it/N2qt/0

the compiler tells you "undefined variable goodmorning()" (you have a typo, check the names are well written), and that's because the order of definition of function in python matters, so the code, to work, should be rewritten like this to doesn't work:

def hello():
    print("hello")
    good_morning()

hello()

def good_morning():
    print("good morning")

this brakes with:

hello
Traceback (most recent call last):
  File "python", line 8, in <module>
  File "python", line 3, in hello
NameError: name 'good_morning' is not defined

and the original code (well written) will work:

def hello():
    print("hello")
    good_morning()

def good_morning():
    print("good morning")

hello()

hello
good morning

Upvotes: 0

AlanK
AlanK

Reputation: 9853

If your code is like this then it wont work:

def hello():
    print("hello")
    good_morning()

hello()

def good_morning():
    print("good morning")

>> NameError: name 'good_morning' is not defined

but since your code allows for both methods to be compiled before it calls the hello() method, the code will compile and run:

def hello():
    print("hello")
    good_morning()

def good_morning():
    print("good morning")

hello()

>> Hello
>> good morning

Upvotes: 0

Related Questions