Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to put functions python

I bring a few days working on python coming from Matlab and I have the next doubt:

I had a matlab program with a lot of functions defined at the end of my m-file. Matlab recognizes those functions even if I call them at the beginning and they are defined at the bottom of my code.

Now, with python, I don't know what is the best way to put the functions because python needs to know the definition of the functions before calling them. I don't want to create a new file for each function. I would like to put all functions together but I can't figure it out. I hope you can help me.

Thx,

like image 719
tete Avatar asked Apr 16 '26 09:04

tete


1 Answers

Another way you can have all the functions is to add a function that does everything you want it to do:

def main():
    #do stuff
    f()
    g()
    ...

And add this to the end of the file:

if __name__ == '__main__':
    main()

This will only execute if your file is the main file. If you import your file from another file, then it won't execute all the code in main().

like image 86
Jmac Avatar answered Apr 17 '26 23:04

Jmac



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!