Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should function be defined before it is used in python?

should the functions be defined before it is used? but why the following code works:

def main():
    dog()

def dog():
    print("This is a dog.")

if __name__ == '__main__':
    main()

I mean the dog() is defined after it is called, how this works?

like image 264
user2131316 Avatar asked Oct 24 '25 10:10

user2131316


1 Answers

Actually it's not (defined after it's called). This script will do the following:

  • create function and assign it to "main"
  • create function and assign it to "dog"
  • call "main"

At that point dog is already known in global scope and main can call it.

like image 193
viraptor Avatar answered Oct 26 '25 00:10

viraptor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!