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 settype() Function

PHP settype() Function The settype() function in PHP is used to set the type of variable var to type. Syntax settype ( mixed &$var , string $type ) Parameter var(required)- This parameter represents the variable being converted. type(required)- This parameter represents the type of variable that is needed.  The possible values of type are...

1 minute read.

PHP Echo And Print

In PHP, echo and print is used to get output data to the screen but there is some difference, between echo and print. PHP echo PHP echo is used to display the...

1 minute read.

WordPress Plugin

WordPress Plugin is a process used to add or extend the functionality which can be enabled or disabled, and it does not interfere with the software and its code. WordPress is lightweight and smooth...

2 minutes read.

PHP array_pop() Function

PHP array_pop() Function The array_pop() function in PHP pops or removes the last element from the array shortening the array by one element. Syntax array_pop ( array &$array ) Parameter array(required)- This parameter represents the input array to get the value...

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 natsort() Function

PHP natsort() Function The natsort() function in PHP Sort an array using a case insensitive "natural order" algorithm while maintaining the keys. Syntax natsort ( array &$array ) Parameter array(required)- This parameter represents the input array. Return This parameter returns a Boolean value TRUE on success or FALSE on...

1 minute read.

PHP strval() function

PHP strval() function The strval() function in PHP is used to get the string value for the specified variable. This function cannot be used on arrays or objects, if applied then would return only the...

1 minute read.

PHP strip_tags() Function

PHP strip_tags() Function The strip_tags() function in PHP is sued to strip a string from HTML, XML, and PHP tags. It is a binary-safe function. Syntax strip_tags ( string $str [, string $allowable_tags ] ) Parameter str(required)- This parameter specifies the input string. allowable_tags(optional)- This parameter represents...

1 minute read.

PHP is_countable() Function

The PHP is_countable() function in PHP is used to  find whether a variable is countable or not. It returns a Boolean value true if the parameter var is countable else it returns false. Syntax is_countable ( mixed...

1 minute read.

PHP array_key_exists() function

The array_key_exists () function in PHP is used to check whether the specified key exists in the array or not. It returns a Boolean value TRUE if the given key exists else it returns FALSE. Syntax array_key_exists(mixed key,array$array) Parameter key(required)- This...

1 minute read.

PHP addslashes() Function

PHP addslashes() Function The addslashed() function in PHP is used to return a string with backslashes in front of predefined characters. This function is only used with some characters which are...

1 minute read.

PHP array_slice() Function

PHP array_slice() Function The array_slice() function in PHP is used to extract a slice of the array. It returns the sequence of elements from the array as specified by the offset and length parameters. Syntax array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] ) Parameter array(required)- This array represents the...

2 minutes read.

PHP convert_uudecode() Function

PHP convert_uudecode() Function The convert_uudecode() function in PHP decodes a uuencoded string. Syntax convert_uudecode ( string $data ) Parameter data- This parameter represents the uuencoded data. Return This function returns the decoded data as a string or FALSE on failure. Example 1 <?php // initializing the string $str...

1 minute read.

PHP var_export() Function

PHP var_export() Function The var_export() function in PHP is used to get the structured information for the specified variable. This function outputs or returns a parsable string representation of a variable. This function is similar to...

1 minute read.

PHP lcfirst() Function

PHP lcfirst() Function The lcfirst() function in PHP converts the first character of a string to lowercase if that character is alphabetic. Syntax lcfirst ( string $str ) Parameter str(required)- This parameter signifies the input string. Return This function returns a string with the...

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 Explode() Function

PHP Explode The PHP explode( ) is used to break a string into an array. The PHP explode( ) allow us to break a string into a smaller text with each break...

1 minute read.

PHP is_scalar() Function

PHP is_scalar() Function The is_scalar() function in PHP finds whether a variable is a scalar or not. It returns a Boolean value TRUE if the parameter var is scalar, else it returns FALSE. Scalar variables are those containing an integer, float, string or boolean. This...

1 minute read.

PHP array_push() Function

PHP array_push() Function The array_push() function in PHP pushes one or more elements onto the end of the array. This function increases the length of the array by the number of variables pushed. Syntax array_push ( array &$array, mixed& value [, mixed $... ]...

1 minute read.

PHP asort() function

PHP asort() function The asort() function in PHP is used to sort an array while maintaining the index association. Syntax asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  array(required)- This parameter represents the input array to sort. sort_flags (optional)- This parameter is used to...

1 minute read.