Is there a "main()" function in Python?

Asked

Viewed 4,137 times

7

In some languages, as in C, we have the function main() which is usually the default entry point of the program. There is something similar in Python?

4 answers

8

There is no function main() in Python, at least not explicitly. What we have is '__main__' which is the name of the scope of the code executed in top-level, and is defined in __name__ the name of the module. O '__main__' is defined when the script is executed from the interactive terminal or called by the language interpreter.

You can get a "similar behavior" with the main() as follows:

if __name__ == '__main__':
   main()

This will prevent script content from running when imported:

import meuscript

So whatever’s on the block if will not run on import unless you do:

from meuscript import main
main()

and call the function main() directly.

See on documentation.

6


There is no python function main() as in C. However there is a native variable called __name__ (with two underlines before and after).

In python we have modules that can be executed indepedente or imported in another script. With the variable __name__ it is possible to know if the script is running through an import or directly.

If the script is running through an import, then the variable __name__ takes the name of the imported module. Now if the script is running directly, for example with the command python script.py, then the variable __name__ receives the amount __main__.

More detailed information on this link: https://blog.alura.com.br/o-que-significa-if-name-main-no-python/

5

Python is a language of script then it already begins to exist. In a certain way it exists, but not in the same way as C. It does not formally exist, the code that is found that is not inside a function is taken as a global function, the default input is the script that you have executed, from there it goes executing.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.