Main is the self. Without a main function, the Python code on import would you execute all code.
The main function is where your program starts, the beginning of your program.
So what you can add in your script is:
def main():
print('main')
if __name__ == “__main__”:
main()
On running it will call the function main(). If another script imports this file the functions will be available, but it won't run the code.
So to summarize: 'main' is the name of the scope in which top-level code executes.
There are two ways of using a Python module:
- Run it directly as a script
- import it
When a module is run as a script, its name is set to main.
Main in other languages
The main() function exists in many programming languages, it shows the computer where to start the program. While in Python it's not necessary to put everything in a function, in other languages it is mandatory.
For instance, in C you would write this:
int main()
In Java, a program starts this way:
public static void main(String args[])
So the concept in Python is similar, it's the starting point of your program.
It is generally a good practice to divide your code into small functions, that makes it easier to find bugs and easier to understand. One big long sequence of code is called spaghetti code.
Related links:
Top comments (0)