1

I read the answer given below:

Why use def main()?

It seems it's better practice(?) to put all the code inside a main() function when creating modules to avoid executing it when imported.

But at the same time, when I put all my functions inside main() and I want to import it to another program, how would I call all these functions?

It seems counterproductive to do that but obviously I'm understanding it wrong, so I appreciate any help I could get.

EDIT: So let me know if I understood it, we don't put any actual functions inside main(), they are separate functions. The only thing that will go inside it its the __main__ portion? For example:

Program test.py:

def my_function():
    print('Hello')

def my_function2(num):
    return num*num

print('Hi')

Modified test.py

def my_function():
    print('Hello')

def my_function2(num):
    return num*num

def main():    #so it doesn't execute when imported
    print('Hi')

Is this an accurate way of how you would use the main()?

Community
  • 1
  • 1
tadm123
  • 8,294
  • 7
  • 28
  • 44

2 Answers2

4

main() typically calls your other functions but does not contain them. Your other functions will lie in the body of the script above main() and can be called in the standard way.

So your test.py example could look like this:

def my_function():
    print('Hello')

def my_function2(num):
    return num*num

def main():
    my_function()
    my_function2(5)

if __name__ == "__main__": # if module not imported
    main()
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • HI @Chris_Rands I updated the original post, please let me know if I understood what you said correctly. – tadm123 Nov 24 '16 at 08:51
  • @tadm123 You're not quite right yet, I've edited my answer to show your example. `main()` executes the other functions and the `if __name__ == "__main__":` executes `main()` when the module has not been imported – Chris_Rands Nov 24 '16 at 09:01
1

You call the functions you want to execute within the block below. The functions are assumed to be already defined at the top of your module

if __name__=="__main__":
    call your functions you want to execute 
rabbit
  • 21
  • 4