Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function calling order

How does Python "read in" a program when you run it? For example, I don't understand why there wouldn't be a NameError: name 'cough' is not defined in the below code:

def main():
    for i in range(3):
        cough()


def cough():
    print('cough')


if __name__ == '__main__':
    main()

Basically, my question can also be stated as why do the above and below programs output the same thing:

def cough():
    print('cough')


def main():
    for i in range(3):
        cough()


if __name__ == '__main__':
    main()
like image 478
Vivek Jha Avatar asked Jul 11 '17 03:07

Vivek Jha


1 Answers

Python is an interpreted language which is executed statement by statement (thanks to viraptor's tip: when compiling to bytecode it happens on whole file + per function)

In this case below the program reads line by line and knows that the function cough() and main() are defined. and later when main() is called Python knows what it is and when main() calls cough() Python knows what it is as well.

def cough():
    print('cough')


def main():
    for i in range(3):
        cough()


if __name__ == '__main__':
    main()

In this other case (below) it is the same thing. just that Python learns what main() function is before cough(). Here you might wonder: "why won't python throw an error since it doesn't know what caugh() is inside main() ? " Good question my friend.

But as long as your function is defined before you call it everything is fine. Because remember Python won't "check" if a function is defined until you call it. so in this case even tho cough() is not defined when python is reading function main() it is ok because we didn't call main() until after cough() is defined below.

def main():
    for i in range(3):
        cough()


def cough():
    print('cough')


if __name__ == '__main__':
    main()

Hope this helps you understand Python better.

like image 150
OLIVER.KOO Avatar answered Sep 28 '22 14:09

OLIVER.KOO