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 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.

PHP get_defined_vars() Function

PHP get_defined_vars() Function The get_defined_vars() function in PHP returns an array of all defined variables. It returns a multidimensional array containing a list of all defined variables. Syntax get_defined_vars ( void ) Parameter NA Return This function returns a multidimensional array containing a list...

1 minute read.

PHP sha1_file() Function

PHP sha1_file() Function The sha1_file() in PHP calculates the sha1 hash of a file and returns the hash (40-character hexadecimal number). Syntax sha1_file ( string $filename [, bool $raw_output] )  Parameter filename(required)- This parameter represents the filename of the file to hash. raw_output(optional)- This...

1 minute read.

PHP strtr() Function

PHP strtr() Function The strtr() function in PHP translates or replaces certain characters in a string. Syntax strtr ( string $str , string $from , string $to ) or strtr ( string $str , array $replace_pairs ) Parameter str(required)- This parameter specifies the string to translate from(required)- This parameter represents the string being translated to the parameter ‘to’. to(required)- It specifies what...

1 minute read.

PHP While Loop

PHP while loop is used to run the same block of code until a condition is met. It should be used if number of iteration it not known. Syntax: <?php while (condition){   //Code...

1 minute read.

PHP array_rand() Function

PHP array_rand() Function The array_rand() function in PHP picks one or more random keys out of an array. Syntax array_rand ( array $array [, int $num = 1 ] ) Parameter array(required)- This parameter represents the input array. num(optional)- This parameter specifies how many entries should be picked....

1 minute read.

PHP echo() Function

PHP echo() Function The echo() function in PHP outputs or displays one or more strings. The major differences between print() function and echo() function is that echo accepts an argument list and doesn't have a return value. Also, it is slightly...

1 minute read.

PHP stripcslashes() Function

PHP stripcslashes() Function The stripcslashes() function in PHP returns a string with backslashes(\n, \r ..., octal and hexadecimal representation) stripped off. Syntax stripcslashes ( string $str )  Parameter str(required)- This parameter signifies the string to be unescaped. Return This function returns the unescaped string with backslashes stripped off. Example 1   ...

1 minute read.

PHP str_ireplace() Function

PHP str_ireplace() Function The PHP str_ireplace() function in PHP replaces some characters with some other characters in a string. Syntax str_ireplace ( mixed $search , mixed  $replace , mixed $subject [, int &$count ] ) Parameter search(required)- This parameter specifies the value being searched for. replace(required)- This parameter represents the replacement value...

1 minute read.

PHP uksort() Function

PHP uksort() Function The uksort() function in PHP sorts an array by keys using a user-defined comparison function. Syntax uksort ( array &$array , callable $key_compare_func ) Parameter array(required)- This parameter represents the input array. key_compare_func(required)- This parameter represents a string that describe a callable comparison function....

1 minute read.

PHP strlen() Function

PHP strlen() Function The strlen() function in PHP is used to return the length of the specified string. Syntax strlen ( string $string ) Parameter string(required)- This parameter represents the string which is measured for length. Return This function returns the length of the string on success or returns 0 if the specified...

1 minute read.

PHP Data Types

PHP data type is used to hold the various types of data or value.  There are three types of data types in PHP. It is a loosely data typed language, so...

2 minutes 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 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 strtok() Function

PHP strtok() Function The strtok() function in PHP splits a string into smaller strings or tokenize the specified string.  Syntax strtok ( string $str , string $token ) Parameter str(required)- This parameter represents the input string to split into smaller strings or tokens. token(required)- It signifies...

1 minute read.

PHP str_pad() Function

PHP str_pad() Function The str_pad() function in PHP pads a string to the given length with another string. Syntax str_pad ( string $input , int $pad_length [, string $pad_string  [, int $pad_type ]] ) Parameter input(required)- This parameter signifies the input string. pad_length(required)- This parameter specifies the length of the new string. If this value...

2 minutes read.

PHP print_r() Function

PHP print_r() Function The print_r() function in PHP displays the information stored in a variable. Syntax print_r (mixed $expression [, bool $return] ) Parameter expression(required)- This parameter represents the expression to be printed. return(optional)- This parameter is used to store the output of...

2 minutes read.

PHP Forms

PHP form is used to take input from users, by using superglobals$_REQUEST, $_GET and $_POSTmethod. There are various request methods in PHP Get method Post method Put method Patch method Delete...

5 minutes read.

PHP ksort() Function

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

2 minutes read.

PHP addcslashes() Function

The addcslashed() function in PHP is used to add quote string with slashes in a C style. It is case-sensitive function.  Syntax addcslashes (str, charlist ) Parameter str(required)- This parameter represents the string to be escaped. charlist(required)-...

1 minute read.