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()?

1
  • 2
    You don't put all the functions inside main, you call them from main. Commented Nov 24, 2016 at 7:48

2 Answers 2

5

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() 
Sign up to request clarification or add additional context in comments.

2 Comments

HI @Chris_Rands I updated the original post, please let me know if I understood what you said correctly.
@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
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.