Daniel l
Daniel l

Reputation: 43

How function in python actually works?

I got a question for how a function actually works. From my understanding, the function can be call only if the call() is below the function which seems something like this :

def main():
     num1 = int(input("Please enter first number: "))
     print_num(num1)
main()

But I don't get it why the main() in print_num function can call the def main(), which locate under it.

def print_num(num1):
     print(num1)
     main()

def main():
     num1 = int(input("Please enter first number: "))
     print_num(num1)
main()

Upvotes: 0

Views: 62

Answers (2)

Eshaan Gupta
Eshaan Gupta

Reputation: 614

def print_num(num1):
     print(num1)
     main()

def main():
     num1 = int(input("Please enter first number: "))
     print_num(num1)
main()

The above code is executed in the following order:

(1)def print_num(num1):
(6)     print(num1)
(7)     main()
(2)def main():
(4)     num1 = int(input("Please enter first number: "))
(5)     print_num(num1)
(3)main()

It's about the order in which it has been executed. So even if you write

def print_num(num1)

on line 1, it's body will be the 6th line of code to be executed, that is, only after it has been called. Python will only execute the body of a function after it has been called.

Upvotes: 3

Chris Doyle
Chris Doyle

Reputation: 12209

When you run your python code, only the function definition is read and the function name stored. The code inside the function is not evaluated until it has been called. So for example, the below when run will define the func1 and func2 then when it calls func1 only then the code of func1 is evaluated. At this point the code has already seen the func2 definition so its aware of it and there is no issue.

def func1():
    func2()


def func2():
    print("hello world")

func1()

OUTPUT

hello world

However if we put the call to func1 before func2

def func1():
    func2()

func1()

def func2():
    print("hello world")

In this case func1 is called before the code has even seen func2. So when it evaluates the code in func1 its no idea what func2 is and we get an error.

Traceback (most recent call last):
  File "C:/Users/cdoyle5/PycharmProjects/stackoverflow/chris.py", line 4, in <module>
    func1()
  File "C:/Users/cdoyle5/PycharmProjects/stackoverflow/chris.py", line 2, in func1
    func2()
NameError: name 'func2' is not defined

Upvotes: 4

Related Questions