0

I have been working on a python course on linked learning.The following was said in the course "Python does not support forward declaration but the line if __name__ == '__main__': main() enables forward declaration".

Then I tried the following code:

main()
def main():
    kitten()
def kitten():
    print('meow')

And it worked just fine. Now I'm confused about the python flow.

I would like to understand even when kitten() was defined after it was called how did it still run.

Thanks in advance.

Alexis Philip
  • 517
  • 2
  • 5
  • 23
Mrak Vladar
  • 598
  • 4
  • 18
  • Does this answer your question? [Make function definition in a python file order independent](https://stackoverflow.com/questions/758188/make-function-definition-in-a-python-file-order-independent) – Stidgeon Jan 20 '20 at 03:52
  • 3
    Are you sure it is the only code you ran, beacuse that program will give you the error NameError: name 'main' is not defined – Sriteja Sugoor Jan 20 '20 at 03:53
  • 1
    your program probably only ran because you had some things predefined in memory. Restart kernel, run the code in the order you wrote, and it will fail. – Paritosh Singh Jan 20 '20 at 03:54
  • @ParitoshSingh You are right sir, I had run a version of the code with the `if __name__ == '__main__': main()` . Thank You. – Mrak Vladar Jan 20 '20 at 03:56
  • @SritejaSugoor You are Right, Thank You. – Mrak Vladar Jan 20 '20 at 03:57

1 Answers1

-1

When the program runs, if a function is encoutered, it is evaluated for syntax and it doesn't execute the function code. If your run the following code

def main():
    kitten()
def kitten():
    print('meow')
main()

it will run fine because, first the main function got evaluated, then kitten function, then the program will call main function which calls kitten function which is already evaluated so it works.

Sriteja Sugoor
  • 574
  • 3
  • 13