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 array_intersect() function

The array_intersect () function in PHP is used to compute the intersection of arrays. It returns an array containing all the entries from array1 that are present in all the other arrays. Syntax array_intersect ( array $array1 , array $array2 [, array $... ]) Parameter array1(required)- This parameter...

1 minute read.

PHP array_column() Function

PHP array_column() Function The array_column() function in PHP is used to return the values from a single column specified in the input array. Syntax array_column (array $input, mixed $column_key [, mixed $index_key]) Parameter input(required)- This parameter represents a multi-dimensional array or an array of...

1 minute read.

PHP str_word_count() Function

PHP str_word_count() Function The str_word_count() function in PHP counts the number of words inside the string and returns the information about words used in a string. String str_word_count( string $string [, int $format [, string $charlist ]] ) Parameter string(required)- This parameter represents the input string. format(required)- This parameterspecifies the...

2 minutes read.

PHP array_reverse() Function

PHP array_reverse() Function The array_reverse() function in PHP returns a new array with the elements in the reversed order. Syntax array_reverse (array $array [, bool $preserve_keys = FALSE ] ) Parameter array(required)- This parameter represents the input array preserve_keys (optional)- This parameter specifies if the function should preserve the keys...

1 minute read.

PHP array_udiff() Function

PHP array_udiff() Function The array_udiff() function in PHP calculates the difference of arrays by using a callback function for data comparison. Syntax array_udiff ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) Parameter array1(required)- This array represents the first input array. array2(required)- This array represents the second input array. array3….(optional)- It...

1 minute read.

PHP array_key_first() function

The array_key_first () function in PHP gets the first key of an array if the specified array is not empty. Syntax array_key_first(array;$array) Parameter array(required)- This parameter signifies the input array. Return This function returns the first key of the specified...

1 minute read.

PHP chop() Function

PHP chop() Function The chop() function in PHP removes whitespaces or other predefined characters from the right end of the specified string. Syntax chop(str,charlist) Parameter str(required)- This parameter specifies the string to check. charlist(optional)- This parameter...

1 minute read.

PHP soundex() Function

PHP soundex() Function The soundex() function in PHP Calculates the soundex key(four character long alphanumeric string that represent English pronunciation of a word) of a string. Syntax soundex ( string $str ) Parameter str(required) – This parameter represents the input string. Return This function returns the soundex...

1 minute read.

PHP sort() Function

PHP sort() Function The sort() function in PHP sorts an array where the elements will be arranged from lowest to highest. Syntax sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  Parameter array(required)- This parameter represents the input array. sort_flags (optional)- This parameter is used to modify the...

1 minute read.

PHP Do While Loop

PHP do while loop is used to execute the code at least one time because condition is checked after executing the code. Syntax: do{ //code to be executed  }while(condition); Output <?php $n=1;  do{ echo "$n<br/>";  $n++;  }while($n<=5);  ?> Output 1 2 3 4 5 ← Prev Next →...

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.

PHP array_merge_recursive() Function

PHP array_merge_recursive() Function The array_merge_recursive() function  in PHP merges the elements of one or arrays together and returns the resulting array. Syntax array_merge_recursive (array $array  , [ array $... ] ) Parameter array(required)- This parameter specifies the input array ….(optional)- It represents more arrays to...

1 minute read.

PHP is_array() Function

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

1 minute read.

PHP is_null() Function

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

1 minute read.

PHP array_udiff_assoc() Function

PHP array_udiff_assoc() Function The array_udiff_assoc () function in PHP computes the difference between the specified arrays with additional index check and compares the data by a callback function. It returns all the values from array1 that are not...

1 minute read.

PHP key_exists() Function

PHP key_exists() Function The key_exists() function in PHP checks if the specified key or index exists in the array or not. Syntax key_exists ( mixed $key , array $array )  Parameter key(required)- This parameter represents the value to check. array(required)- This parameter signifies an input array with...

1 minute read.

PHP key() Function

PHP key() Function The key() function in PHP fetches a key from an array and returns the index element of the current array position. Syntax key ( array $array ) Parameter array(required)- This parameter represents the input array. Return This function returns the key of the...

1 minute read.

PHP vfprintf() Function

PHP vfprintf() Function The vfprintf() function in PHP writes a formatted string to a specified output stream. Syntax vfprintf ( resource $handle , string $format , array $args )  Parameter handle(required)- This parameter represents where to write the string. format(required)- This parameter specifies the string and how to format the...

3 minutes read.

PHP substr_replace() Function

PHP substr_replace() Function The substr_replace() function in PHP replaces a part of a string with another string. Syntax substr_replace (mixed $string , mixed $replacement , mixed $start [, mixed $length ] ) Parameter string(required)- This parameter represents the input string. replacement(required)- This parameter signifies the string to replace with. start(required)-...

2 minutes read.

PHP array() function

PHP array() function The array() function in PHP is used to create an array. Syntax array ([ mixed $... ] ) Parameter …(optional)- This parameter represents the elements’ values along with keys of the array. The syntax of this is as follows: "index => values"...

1 minute read.