Python main() function

What is a main() function?

In most of the programming languages, there is this one special function i.e., main() which is executed firstly everytime when we run the program. The special function is nothing but the main function of the program i.e., main() function as we usually denote it in the code. The main() function of the program is the starting point of the program from where the code is start executing in most of the programming languages. A main() function must have specific return type while defining it in the program and it totally depends upon the requirements and functionality of that particular programming language standards.

main() function in Python

In Python, whenever we are writing a program, we do not need to define the main() function.This is because the Python interpreter runs the program from the very first line of it. The execution of a Python program goes line by line after starting from the first line. Therefore, it does not matter if the main() function is present in the program or not.

Since, we don't have any main() function in our Python program, the interpreter will execute the code from 0 indentation When we give the command in Python to run the program.

Does a Python program need main() function?

Till now, in this tutorial, we have learned that Python interpreter execute the code from very first line and 0 indentation. So, we can conclude that we don't have any compulsion to have a main function in our Python program. Nevertheless, if we have a specified or pre-defined starting point in our program is very useful to understand the functionality of the program. Before looking more into this, let's look at the following example:

Example -

 # Define a main() function with no arguments
 def main():
      print ("Welcome Python Developers!")
 # Using a simple print statement
 print ("This is TutorialAndExample Website for Python tutorial!") 

Output:

This is TutorialAndExample Website for Python tutorial!

Explanation: In the above given code, we have first defined a default main() function in the program and not given any arguments as well as return type in it. After that, we have passed the print statement in the function. In last, after exiting the function, we have used a simple print statement to print a sentence in the output of the program.

As we can see in the output, only the sentence given in simple print statement i.e., "This is TutorialAndExample Website for Python tutorial!" is printed in the output and the print statement defined in the main() function is not printed. This happened because in the program we have not defined the call function i.e., "if__name__ == "__main__" in the program and therefore, the main() will not be called out by the interpreter and it will not print anything as result.

So, we have understood that defining a call function in the program for the main() function is very important and without defining it, we cannot execute the main() function from our Python program. Now, look at the following example, where we will define the call function:

 # Define a main() function with no arguments
 def main():
      print ("Welcome Python Developers!")
 # defining the call function for main() function
 if __name__ == "__main__":
     main()
 # Using a simple print statement
 print ("This is TutorialAndExample Website for Python tutorial!") 

Output:

Welcome Python Developers!
This is TutorialAndExample Website for Python tutorial!

Explanation: Now, we have defined the call function for the main function in the program. And because of this, the main() function will be executed by the interpreter. As we can see in the output, both the print statements have been printed the result in output once we give the command to run the program.

So,we have seen that how important call function is for using and executing the main() function. The call function becomes more important in Python because:

  • When we run the program, the Python interpreter will read the source file and execute all the code present in the file or program.
  • When we run the source file or program as main() function, the interpreter will set thespecial variable (__name__) to have a special value ("__main__") in the program.
  • When we execute the main() function from our Python program, the interpreter needs an if statement to check if the __name__ is equal to __main__ or not.
  • The if__name__ == __main__ in Python also allow us to run the source file or program either as standalone program or reusable files.

The __main__ function

As we know that, to execute the main function, we have to define the __name__ == __main__ in the program as a call function. But what it actually does in the program?

If we are running the program or script directly in the Python, it will assign the __main__ to __name__ (It all happens in the background while we are writing the program). And this will end up, we are writing the conditional statement i.e., if__name__ == __main__ to check if the assignment is done or not. And, if Python evaluates this condition as to be true, then it means that the file is executed directly.

Let's look at following program as one more example:

 # Using a simple print statement
 print("This is simple print statement!")
 # Define a main() function with no arguments
 def main():
     print("Main function is executed successfully")
 # Defining the call function
 if __name__=="__main__":
     main() 

Output:

 This is simple print statement!
 Main function is executed successfully 

So, if we are running the program directly in the program, this condition is always going to be true as by default in the Python. Or in short, we can say that the if condition is used to check if we are running the Python script directly or importing it to execute the main() function in the program.

Now, let's try to learn about this a little bit more by using the main() function as a module in the Python script or program.

Using __Main__ function as a module

When we use the main() function as a module by using a Python script, then the __name__ variable we defined in the program will get the name of the script we imported as value in it.

To import a Python script, first we have to create one. Write the following Python program in the Python shell:

 # Using a print statement
 print("The first file name i.e., __name__ = %s" %__name__)
 # Defining the if else statement for main function
 if __name__ == "__main__": 
     print("The first file is being run directly in Python")
 else:
     print("The first file is being imported in Python") 

Output:

 The first file name i.e., __name__ = __main__
 The first file is being run directly in Python 

We have tosave this program as a script file in the device in order to import in the other program.

Now, write down the following program in Python shell and also import the script file in it that we have saved:

 # Importing the first file as script file in the program
 import changing
 # Using a simple print statement to print the __name__ variable
 print("The second Python file name i.e., __name__ = %s" %__name__)
 # Using the if else statement to print the result of execution of main function
 if __name__ == "__main__":
     print("The second Python file is being run directly in Python")
 else:
     print("The second Python file is being imported in Python") 

Output:

 The first file name i.e., __name__ = changing
 The first file is being imported in Python
 The second Python file name i.e., __name__ = __main__
 The second Python file is being run directly in Python 

As, we can see in the output that when we run the first file directly, the interpreter assigned the value of __name__ variable equals to __main__. But, when we run the second file by importing the first file in the program, then the interpreter assigned the value of __name__ variable equals to the name of the first file.

That's how by the if statement, it is checked that if the main function of program is running directly on Python or a script file is imported in the program to execute the main() function.

Conclusion:

In this tutorial, we have learned about the main() function present in Python. We have also learned about that how we can execute the main function in the Python both by running directly the source file and by importing the script file in the program. We have also understood what is the difference between if condition execution both when the script file is imported and when the source file is run directly.


Related Topics

PHP Variables

PHP Variable is the name of memory location used to hold the data.  In PHP, variable starts with $ symbol. Rules for PHP Variables. Variable starts with $ sign. Variable name...

2 minutes read.

PHP is_float() Function

The PHP is_float() function in PHP is used to  find whether the type of the specified variable is a float or not. It returns a Boolean value true if the parameter var is...

1 minute read.

PHP array_intersect_assoc() function

PHP array_intersect_assoc() function The array_intersect_assoc() function in PHP is used to compute the intersection of arrays with the help of an additional index check. It returns an array containing all the entries from array1 that are present...

1 minute read.

PHP metaphone() Function

PHP metaphone() Function The metaphone() function in PHP calculates the metaphone key (representing how a string sounds or pronounced) of a string. This function is used to text search and text matching or spelling...

1 minute read.

Python if-else

Python if-else The else statement is associated with if statement. An else statement executes if the conditional expression in if the statement becomes false or a Zero value. If the conditional expression...

2 minutes read.

PHP Include Function

PHP Include( ) The PHP include() statement holds all the code/text that liesin the defined file and paste it into the file that uses the "include" statement. With the help of include...

3 minutes read.

PHP number_format() Function

PHP number_format() Function The number_format() function in PHP formats a number with grouped thousands. This function accepts one, two, or four parameters (not three): Syntax number_format ( float $number [, int $decimals ] )             or number_format ( float $number , int $decimals  , string $dec_point, string$thousands_sep ) Parameter number(required)- This parameter represents the number to be formatted. If...

1 minute read.

PHP sscanf() Function

PHP sscanf() Function The sscanf() function in PHP parses input from a string according to a given format. Syntax sscanf ( string $str , string $format [,mixed &$arg1,$agr2,$arg++... ] ) Parameter str(required)- This parameter specifies the string to read. format(required)- This parameter specifies the format to use. The conversion specification...

3 minutes read.

PHP array_replace() Function

PHP array_replace() Function The array_replace() function in PHP replaces the elements from passed arrays into the first array with values having the same keys in each of the following arrays. Syntax array_replace ( array $array1 [, array $... ] ) Parameter array(required)- This parameter represents...

1 minute read.

PHP str_getcsv() Function

PHP str_getcsv() Function The str_getcsv() function in PHP parses a CSV string into an array and returns an array containing the fields read. Syntax str_getcsv ( string $input [, string $delimiter [, string $enclosure [, string$escape ]]] ) Parameter input(required)- This parameter represents the string to parse. delimiter(optional)- This parameter signifies...

1 minute read.

PHP is_long() Function

The PHP is_long () function in PHP is used to find whether a variable is an integer or not. It returns a Boolean value true if the parameter var is integer else it returns...

1 minute read.

PHP parse_str() Function

PHP parse_str() Function The parse_str() function in PHP parses a query string into variables. Syntax parse_str ( string $encoded_string [, array &$result ] ) Parameter encoded_string(required)- This parameter represents the input string. result(optional)- This parameter specifies the name of an...

1 minute read.

PHP array_values() Function

PHP array_values() Function The array_values () function in PHP returns all the values from the array and indexes the array numerically. Syntax array_values ( array $array ) Parameter array(required)- This array represents the input array. Return This function returns an indexed array of values. Example 1 Output Input Array: Array ...

1 minute read.

Python Set pop() method

Python Set pop() method The set.pop() method in Python removes an arbitrary element (random item) from the set and returns the element removed. Syntax set.pop()  Parameter NA Return This method returns an arbitrary (random) element from the set. Example 1 #...

1 minute read.

PHP MySQL Database Tutorial

MySQL is the most popular database system that is used within PHP. Let's first understand about MySQL. What is MySQL? MySQL is open-source Relational Database Management System (RDMS). The name of MySQL is...

13 minutes read.

PHP sizeof() Function

PHP sizeof() Function The sizeof() function in counts all elements and return the size of the array. This function is an alias of count(). Syntax sizeof( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )  Parameter array_or_countable(required)– This parameter represents the input array or countable object. mode(optional)-...

1 minute read.

PHP array_diff_assoc() Function

PHP array_diff_assoc() Function The array_diff_assoc() Function in PHP compares the difference of arrays and returns an array containing all the values from array1 that are not present in any of the other arrays. Syntax array_diff_assoc ( array $array1 , array $array2 [, array $... ] ) Parameter array1(required)- This parameter signifies...

1 minute read.

PHP strrrev() Function

PHP strrrev () Function The strrev() function in PHP reverses a string. Syntax strrev ( string $string ) Parameter string(required)- This parameter represents the input string to be reversed. Return This function returns the reversed string. Example 1 Output Initial string: Hello...

1 minute read.

PHP krsort() Function

PHP krsort() Function The krsort() function in PHP sorts an array by key in reverse order while maintaining the keys. Syntax krsort (array & $array[,int $sort_flags= SORT_REGULAR] ) Parameter array(required)- This parameter represents the input array. sort_flags(optional)- This...

3 minutes read.

PHP array_intersect_ukey() function

The array_intersect_ukey () function in PHP is used to compute the intersection of arrays with the help of a callable function on the keys for comparison. It returns an array containing all the...

1 minute read.