---
description: What is Python main function? Why use def main() function and Python main method with example in this tutorial.
title: "Python Main Function &#038; Method: Understand def Main()"
image: https://www.guru99.com/images/python-main-function-and-method.png
---

[Skip to content](#main)

**⚡ Smart Summary**

Python main function marks the starting point where the interpreter begins running a program. Defined with def main() and paired with the if \_\_name\_\_ == “\_\_main\_\_” guard, it separates reusable module code from standalone script execution.

- 🚀 **Entry point:** The main function defines where execution begins, so readers can follow a program’s flow from one clear starting place.
- 🧩 **def main()::** Wrapping logic inside def main() keeps setup and execution separate from function and class definitions.
- 🔒 **\_\_name\_\_ guard:** The if \_\_name\_\_ == “\_\_main\_\_” check runs main() only on direct execution, never on import.
- 🔁 **Reusable modules:** Guarded code lets other scripts import your functions without triggering the whole program.
- ⌨️ **Command-line input:** A main() function is the natural place to read sys.argv arguments and return an exit status.
- 🤖 **AI assistance:** AI assistants such as GitHub Copilot scaffold main() boilerplate and the \_\_name\_\_ guard from a short prompt.

Read More

![Python Main Function](https://www.guru99.com/images/python-main-function-and-method.png)

## What is Python Main Function?

The **Python main function** is the starting point of any program. When the program is run, the Python interpreter runs the code sequentially. The main function is executed only when it is run as a Python program. It will not run the main function if it is imported as a module.

What is the def main() function in Python? To understand this, consider the following example code, which is part of the core [Python programming](https://www.guru99.com/python-tutorials.html) basics:

### def main() Example 1

```
def main():
     print ("Hello World!")
print ("Guru99")

```

[![Python Main Function]()](https://www.guru99.com/images/Pythonnew/Python4_1.png)

Here, we got two pieces of print- one is defined within the main function that is “Hello World!” and the other is independent, which is “Guru99”. When you run the function def main ():

- Only “Guru99” prints out
- and not the code “Hello World!”

It is because we did not declare the call **function “if\_\_name\_\_== “\_\_main\_\_”.**

It is important that after defining the main function, you call the code by if\_\_name\_\_== “\_\_main\_\_” and then run the code, only then you will get the output “hello world!” in the programming console. Consider the following code

### def main() Example 2

```
def main():
    print("Hello World!")

if __name__ == "__main__":
    main()

print("Guru99")

```

Guru99 is printed in this case.

[![Python Main Function]()](https://www.guru99.com/images/Pythonnew/Python4_22.png)

Here is the explanation,

- When Python interpreter reads a source file, it will execute all the code found in it.
- When Python runs the “source file” as the main program, it sets the special variable (\_\_name\_\_) to have a value (“\_\_main\_\_”).
- When you execute the main function in python, it will then read the “if” statement and checks whether \_\_name\_\_ does equal to \_\_main\_\_.
- In Python **“if\_\_name\_\_== “\_\_main\_\_”** allows you to run the Python files either as **reusable modules or standalone programs.**

## Why Use a main() Function in Python?

Python does not force you to write a main function, yet experienced developers use one in almost every non-trivial script. The def main() pattern brings order to a file and makes the code safe to reuse. Here are the main reasons to use it:

- **Clear entry point:** A main() function tells any reader exactly where the program starts, so the logic is easy to follow.
- **Reusable modules:** Code guarded by if \_\_name\_\_ == “\_\_main\_\_” runs only on direct execution, so other files can import your functions without side effects.
- **Local scope:** Variables created inside main() stay local, which avoids accidental clashes with global names elsewhere in the module.
- **Easier testing:** Isolating logic in main() lets a test suite call it directly and check the result.
- **Shared convention:** A main() function is a widely recognized signal of the program entry point, which improves maintainability across teams.

**Don't Miss:**

- [Python Conditional Statements: IF…Else, ELIF & Switch Case](https://www.guru99.com/if-loop-python-conditional-structures.html)
- [Python Tutorial PDF: Basics for Beginners (Download Notes)](https://www.guru99.com/python-tutorial-pdf.html)
- [Python with MySQL Connectivity: Database & Table \[Examples\]](https://www.guru99.com/python-mysql-example.html "Python with MySQL Connectivity: Database & Table [Examples]")
- [How to Run Python Scripts: Step by Step Guide](https://www.guru99.com/run-python-scripts.html)

In short, a main() function is optional in Python, but it keeps larger programs readable, testable, and safe to import.

## The \_\_name\_\_ variable and Python Module

To understand the importance of \_\_name\_\_ variable in Python main function method, consider the following code:

```
def main():
    print("hello world!")

if __name__ == "__main__":
    main()

print("Guru99")

print("Value in built variable name is:  ",__name__)

```

[![The \_\_name\_\_ variable and Python Module]()](https://www.guru99.com/images/2/python-main-function-new-03.png)

Now consider, code is imported as a module

```
import MainFunction

print("done")

```

[![The \_\_name\_\_ variable and Python Module]()](https://www.guru99.com/images/2/python-main-function-new-04.png)

**Here, is the code explanation:** Like C, Python uses == for comparison while = for assignment. Python interpreter uses the main function in two ways

**direct run:**

- \_\_name\_\_=\_\_main\_\_
- if statement == True, and the script in \_main\_will be executed

**import as a module**

- \_\_name\_\_= module’s filename
- if statement == false, and the script in \_\_main\_\_ will not be executed

When the code is executed, it will check for the module name with “if.” This mechanism ensures, the main function is executed only as direct run not when imported as a module.

Above examples are Python 3 codes, if you want to use Python 2, please consider following code

```
def main():
  print "Hello World!"
  
if __name__== "__main__":
  main()

print "Guru99"

```

In Python 3, you do not need to use if\_\_name. Following code also works

```
def main():
  print("Hello World!")
  
main()
print("Guru99")

```

**Note:** Make sure that after defining the main function, you leave some indent and not declare the code right below the def main(): function otherwise, it will give indent error.

## How to Pass Command-Line Arguments to the Python main() Function

A main() function is the natural place to handle input that a user passes on the command line. Python stores these values in the sys.argv list, which the standard sys module provides. The first item, sys.argv\[0], is the script name, and every value after it is an argument supplied by the user.

The following example reads and prints command-line arguments from inside a main() function:

```
import sys

def main():
    print("Script name:", sys.argv[0])
    print("Arguments passed:", sys.argv[1:])

if __name__ == "__main__":
    main()
```

If you save the file as script.py and run **python script.py alpha beta**, the program prints the script name and the list \[‘alpha’, ‘beta’]. Because the values arrive inside main(), the logic stays organized and easy to test.

Here are a few practical tips when working with command-line input:

- **Slice off the script name:** Use sys.argv\[1:] to read only the arguments the user typed.
- **Use argparse for real tools:** The built-in argparse module parses flags, options, and help text far more safely than reading sys.argv by hand.
- **Return an exit code:** Wrap the call as sys.exit(main()) so the return value of main() becomes the process exit status.
- **Validate early:** Check the number and type of arguments at the top of main() before running the rest of the program.

This pattern turns a simple script into a reliable command-line tool while keeping every step inside a single, testable main() function.

## Python main() Function vs Other Programming Languages

Developers coming from C, C++, or Java often expect a mandatory main() function. Python works differently because it is an interpreted language, so the interpreter simply runs a file from the top line to the bottom. The main() function in Python is therefore a convention rather than a rule.

- **C, C++, C#, and Java:** A main() function is a required entry point. The runtime automatically calls it, and there can be only one per program.
- **Python:** No main() function is required. Execution starts at the first line of the file, and def main() runs only if your code calls it.
- **The guard:** The if \_\_name\_\_ == “\_\_main\_\_” block gives Python a purpose similar to a compiled main() by marking code that should run only when the file is the main program.

So while other languages enforce a main() entry point, Python leaves the choice to you, offering the same clarity through convention instead of a compiler rule.

This code is editable. Click Run to Execute  

  

## FAQs

🧭 What is the difference between \_\_main\_\_ and main() in Python?

\_\_main\_\_ is the name Python gives the top-level script, detected through the \_\_name\_\_ variable. main() is an ordinary user-defined function that holds your program logic. They work together, but \_\_main\_\_ is an environment name while main() is a function.

📌 Why is the if \_\_name\_\_ == “\_\_main\_\_” block placed at the bottom of a script?

Placing it last ensures Python has already defined every function and class above before the block calls main(). Running it earlier could reference names that are not yet defined and raise a NameError.

🏷️ Does the entry function have to be named main() in Python?

No. Python attaches no special meaning to the name main. You may call the entry function anything you like, yet naming it main() is a strong convention that signals the program’s starting point to other developers.

↩️ Can the Python main() function return a value?

Yes. A main() function can return a value, and a common pattern writes sys.exit(main()) so that return becomes the process exit code. Returning 0 signals success, while a non-zero value signals an error.

⚠️ What happens if you call main() without the if \_\_name\_\_ guard?

Without the guard, main() runs both when the file is executed directly and when it is imported. Other programs that only wanted to reuse its functions would trigger unwanted execution and side effects.

⌨️ Why does Python raise an IndentationError after def main():?

The body of main() must be indented beneath the def main(): line. Writing the next statement flush-left leaves the function without an indented block, so Python raises an IndentationError. Add consistent spaces or a tab.

🤖 How can GitHub Copilot help write a Python main() function?

GitHub Copilot autocompletes the def main() skeleton and the if \_\_name\_\_ == “\_\_main\_\_” guard from a short comment. It also suggests argument parsing and docstrings, letting you focus on the program logic instead of boilerplate.

🧠 Why is a main() function useful in AI and machine learning Python scripts?

In AI and machine learning projects, a main() function is the entry point for training or inference scripts. It reads hyperparameters from command-line arguments, keeps utilities importable for reuse, and makes experiments easier to test and automate.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/python-main-function-and-method.png","url":"https://www.guru99.com/images/python-main-function-and-method.png","width":"700","height":"250","caption":"Python Main Function &amp; Method","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/python","name":"Python"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html","name":"Python Main Function &#038; Method: Understand def Main()"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html#webpage","url":"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html","name":"Python Main Function &#038; Method: Understand def Main()","dateModified":"2026-10-07T13:34:54+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/python-main-function-and-method.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/editorial","name":"Editorial Team","url":"https://www.guru99.com/author/editorial","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/favicon-new-logo.png","url":"https://www.guru99.com/images/favicon-new-logo.png","caption":"Editorial Team","inLanguage":"en-US"},"sameAs":["https://www.guru99.com/editorial-team"],"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Python","headline":"Python Main Function &#038; Method: Understand def Main()","description":"What is Python main function? Why use def main() function and Python main method with example in this tutorial.","keywords":"python","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/editorial","name":"Editorial Team"},"dateModified":"2026-10-07T13:34:54+05:30","image":{"@id":"https://www.guru99.com/images/python-main-function-and-method.png"},"copyrightYear":"2026","name":"Python Main Function &#038; Method: Understand def Main()","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between __main__ and main() in Python?","acceptedAnswer":{"@type":"Answer","text":"__main__ is the name Python gives the top-level script, detected through the __name__ variable. main() is an ordinary user-defined function that holds your program logic. They work together, but __main__ is an environment name while main() is a function."}},{"@type":"Question","name":"Why is the if __name__ == \u201c__main__\u201d block placed at the bottom of a script?","acceptedAnswer":{"@type":"Answer","text":"Placing it last ensures Python has already defined every function and class above before the block calls main(). Running it earlier could reference names that are not yet defined and raise a NameError."}},{"@type":"Question","name":"Does the entry function have to be named main() in Python?","acceptedAnswer":{"@type":"Answer","text":"No. Python attaches no special meaning to the name main. You may call the entry function anything you like, yet naming it main() is a strong convention that signals the program\u2019s starting point to other developers."}},{"@type":"Question","name":"Can the Python main() function return a value?","acceptedAnswer":{"@type":"Answer","text":"Yes. A main() function can return a value, and a common pattern writes sys.exit(main()) so that return becomes the process exit code. Returning 0 signals success, while a non-zero value signals an error."}},{"@type":"Question","name":"What happens if you call main() without the if __name__ guard?","acceptedAnswer":{"@type":"Answer","text":"Without the guard, main() runs both when the file is executed directly and when it is imported. Other programs that only wanted to reuse its functions would trigger unwanted execution and side effects."}},{"@type":"Question","name":"Why does Python raise an IndentationError after def main():?","acceptedAnswer":{"@type":"Answer","text":"The body of main() must be indented beneath the def main(): line. Writing the next statement flush-left leaves the function without an indented block, so Python raises an IndentationError. Add consistent spaces or a tab."}},{"@type":"Question","name":"How can GitHub Copilot help write a Python main() function?","acceptedAnswer":{"@type":"Answer","text":"GitHub Copilot autocompletes the def main() skeleton and the if __name__ == \u201c__main__\u201d guard from a short comment. It also suggests argument parsing and docstrings, letting you focus on the program logic instead of boilerplate."}},{"@type":"Question","name":"Why is a main() function useful in AI and machine learning Python scripts?","acceptedAnswer":{"@type":"Answer","text":"In AI and machine learning projects, a main() function is the entry point for training or inference scripts. It reads hyperparameters from command-line arguments, keeps utilities importable for reuse, and makes experiments easier to test and automate."}}]}],"@id":"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html#schema-1139429","isPartOf":{"@id":"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html#webpage"}}]}
```
