🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeMain function python: Write and Run It

To write and run a Python program, you can put its startup work in a function named main(). A check of __name__ == "__main__" calls that function when the file runs as the top-level program and skips that call when another file imports it.
I’ll show how to use a guarded main() function and pass arguments to it.
TL;DR
A Python main function is an ordinary function called from a name guard when its file is the top-level program.
- Define reusable functions first, then write def main():.
- Call it under if __name__ == "__main__": to avoid calling it on import.
- Pass command-line values into main when you want to test or reuse the program.
What Is a Python Main Function?
Python has no reserved entry-function name. The familiar main name is an ordinary function that a program chooses to call.
When Python runs a file or package command, its top-level module receives the special name __main__. The guard distinguishes top-level execution from import.
| How Python starts the module | Typical __name__ | Guard calls main? |
|---|---|---|
| python app.py | __main__ | Yes |
| python -m app | __main__ for the top-level module | Yes |
| import app | app or its package path | No |
How to Write and Run a Python Main Function
A short entry function keeps startup work together.
Step 1: Define the function and guard
Save this as main_example.py. The greeting function is reusable. Function definitions alone produce no output.
def greet(name):
return f"Hello, {name}!"
def main():
print(greet("Asha"))
if __name__ == "__main__":
main()
Run the file from its directory with the command shown below. The direct-run output is:
Hello, Asha!

I ran python3 main_example.py and got Hello, Asha!. The output confirms the guard reached the entry function.
Step 2: Import the module from another file
Save import_example.py beside the first file. The importer can use the imported module’s public functions by name.
import main_example
print("Imported without calling main")
Run the importing file from its directory. The output is:
Imported without calling main

I ran the importing script and saw only its own message.
Step 3: Pass arguments into main
For command-line input, accept an argument list so callers can supply values directly and tests do not need to replace the process-wide argument list.
import argparse
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args(argv)
print(f"Hello, {args.name}!")
if __name__ == "__main__":
main()
With no explicit list, argparse reads the command line. Another module can call the entry function with [“Asha”] to supply the same positional value as a list. The standard library’s argparse tutorial explains options and validation.
For an importable module, python3 -m app runs that module as the top-level program, so its guard is true. The file form, python3 app.py, starts a script by path. Use the invocation documented for the project because it determines how Python locates the code.
For a package command, Python looks for package/__main__.py. It can import main from a command module and call it under its guard, leaving the implementation available to other code.
The guard controls only the call beneath it. Python still executes top-level statements while importing a module, so place startup actions such as prompting for input inside functions. This keeps importing the module from unexpectedly starting the program.
Keep parsing at the command boundary. argparse can convert an input to the type your worker expects and reject malformed values before the main task begins. The worker can then receive a normal Python value, rather than reading sys.argv or deciding how errors should appear in the terminal.
For a command module that returns a status integer, call raise SystemExit(main()) in the entry file. Python then exposes that integer as the process status. A reusable function that returns ordinary data should leave conversion to an exit status to the command-line layer.
Main Function Edge Cases
A misspelled or undefined function call fails when execution reaches that line. Returning a status code also needs an explicit handoff to the process-exit mechanism.
| Case | What happens | Useful fix |
|---|---|---|
| main has no definition | NameError: name ‘main’ is not defined | Define it before the guard or correct the name. |
| Import-time work sits outside the guard | Those statements run during import. | Move startup actions into functions and call them from main(). |
| main() returns a status value | Calling main() alone does not set the process exit status. | Use sys.exit(main()) when returning an integer status. |
I intentionally called an undefined function and got this error:
NameError: name 'main' is not defined. Did you mean: 'min'?
The error shows Python reached an undefined name. Define the function before the guard or correct the name. For process status handling, the __main__ documentation recommends passing an integer return value to sys.exit().
Conclusion
Use a small entry function when a file needs a clear command-line starting point.
For related reading, see AskPython’s if statement guide and file open guide. The official Python modules tutorial covers running and importing modules.
FAQ
These short answers cover common questions about Python’s main convention.
Does Python require a main() function?
No. Python runs module-level statements when a file is executed. main() is a convention that groups a program’s startup work.
Can another file call an imported module’s main()?
Yes. Import the module and call module.main() explicitly. The name guard prevents an automatic call during import, but it does not make the function private.
Why use if __name__ == “__main__”?
The check is true for the top-level module run as a script or with -m. It is false when that module is imported under its module name.


