You've not called your main function at all, so the Python interpreter won't call it for you.

Add this as the last line to just have it called at all times:

main()

Or, if you use the commonly seen:

if __name__ == "__main__":
    main()

It will make sure your main method is called only if that module is executed as the starting code by the Python interpreter. More about that here: What does if __name__ == "__main__": do?

If you want to know how to write a 'main' function, Guido van Rossum (the creator of Python) wrote about it in 2003.

Answer from user764357 on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ __main__.html
__main__ โ€” Top-level code environment
If the file is part of a package, ... environment, its __name__ is set to the string '__main__'. __main__ is the name of the environment where top-level code is run. โ€œTop-level codeโ€ is the first user-specified Python ...
๐ŸŒ
Real Python
realpython.com โ€บ python-main-function
Defining Main Functions in Python โ€“ Real Python
December 21, 2023 - This function is usually called main() and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-main-function
Python Main Function - GeeksforGeeks
August 9, 2024 - File1 __name__ = File1 File1 is being imported File2 __name__ = __main__ File2 is being run directly ยท As seen above, when File1.py is run directly, the interpreter sets the ... and when it is run through File2.py by importing, the __name__ variable is set as the name of the python script, i.e.
๐ŸŒ
Substack
mostlypython.substack.com โ€บ mostly python โ€บ do you really need a main() function?
Do you really need a main() function? - Mostly Python
September 26, 2023 - Thereโ€™s a conditional block, which includes two things unfamiliar to people who are new to programming: __name__ and "__main__".1 ยท Overall, this program uses three lines of boilerplate to run a single line of code. Sometimes there are good reasons to use this kind of structure. But I donโ€™t think it should be used in early examples of Python scripts, and I donโ€™t think people should adopt it as a convention for all their scripts. One of the most common reasons for using this structure in a program relates to how code is imported in Python. When a file is imported, Python runs all the code in the file.
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ the perfect script structure... where do you write the main() function?
r/Python on Reddit: The perfect script structure... Where do you write the main() function?
April 11, 2021 -

Well, I'm trying to figure out what is the best way to write one-file Python programs in terms of structure.

For the purpose of this post I will focus only in the use of the main() function.

Most people out there will write their one-file program this way:

# ...imports, globals, constats...

def first_thing_to_do():
    do stuff

def second_thing_to_do()
    do more stuff

def main():
    first_thing_to_do()
    second_thing_to_do()

if __name__ == "__main__":
    main()

But I think the more logical and readable order for a human is:

# ...imports, globals, constats...

def main():
    first_thing_to_do()
    second_thing_to_do()

def first_thing_to_do():
    do stuff

def second_thing_to_do()
    do more stuff

if __name__ == "__main__":
    main()

In the second way, a programmer that reads the Python program for the first time (or after some months) can see what the program does at first, and then how it does it, not the other way.

In other words, I used to write the problem definition as the main function on top (right next to imports, globals and constants), and the implementation at the bottom, as it is the most abstract (and less likely to change) part of the program.

I know Python can read it in both ways, but all the code I see on the internet use the first structure and I want to know if am I missing something or if it is just a matter of preference.

How do you write your own one-file scripts?

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ what does def main mean in python?
r/learnpython on Reddit: What does def main mean in Python?
September 30, 2024 -

Hi, I just wanted someone to explain to me in a simple way what def main means in Python. I understand what defining functions means and does in Python but I never really understood define main, (but I know both def main and def functions are quite similar though). Some tutors tries to explain to me that it's about calling the function but I never understood how it even works. Any answer would be appreciated, thanks.

Find elsewhere
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-main-function
How to Use the Python Main Function | DigitalOcean
March 19, 2026 - The Python main function is the conventional entry point for a script: you define a function (typically named main) that holds your program logic and call it only when the file is run directly, not when it is imported as a module.
๐ŸŒ
practical-python
dabeaz-course.github.io โ€บ practical-python โ€บ Notes โ€บ 03_Program_organization โ€บ 05_Main_module.html
3.5 Main module - Practical Python Programming
Whatever file you give to the interpreter at startup becomes main. It doesnโ€™t matter the name. It is standard practice for modules that run as a main script to use this convention: # prog.py ... if __name__ == '__main__': # Running as the main program ... statements ...
Top answer
1 of 6
514

Often, a Python program is run by naming a .py file on the command line:

$ python my_program.py

You can also create a directory or zipfile full of code, and include a __main__.py. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py automatically:

$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program

You'll have to decide for yourself whether your application could benefit from being executed like this.


Note that a __main__ module usually doesn't come from a __main__.py file. It can, but it usually doesn't. When you run a script like python my_program.py, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn't necessarily mean you should be looking for a __main__.py file.

2 of 6
215

What is the __main__.py file for?

When creating a Python module, it is common to make the module execute some functionality (usually contained in a main function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

You can get the same semantics for a Python package with __main__.py, which might have the following structure:

.
โ””โ”€โ”€ demo
    โ”œโ”€โ”€ __init__.py
    โ””โ”€โ”€ __main__.py

To see this, paste the below into a Python 3 shell:

from pathlib import Path

demo = Path.cwd() / 'demo'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')

from demo import main

main()
""")

We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py (but not the main function):

>>> import demo
demo/__init__.py executed

When we use the package as the entry point to the program, we perform the code in the __main__.py, which imports the __init__.py first:

$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed

You can derive this from the documentation. The documentation says:

__main__ โ€” Top-level script environment

'__main__' is the name of the scope in which top-level code executes. A moduleโ€™s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == '__main__':
     # execute only if run as a script
     main()

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.

Zipped

You can also zip up this directory, including the __main__.py, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:

from pathlib import Path

demo = Path.cwd() / 'demo2'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')

from __init__ import main

main()
""")

Note the subtle change - we are importing main from __init__ instead of demo2 - this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m flag.

Particularly relevant to the question - zipapp causes the zipped directory to execute the __main__.py by default - and it is executed first, before __init__.py:

$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed

Note again, this zipped directory is not a package - you cannot import it either.

๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-main.html
Python main() - Command Line Arguments
The file affirm.py has all three command line options working: -affirm, -hello, -n ยท You can run the program to see what it does, and look at the main() code as an example.
๐ŸŒ
FastAPI
fastapi.tiangolo.com โ€บ tutorial โ€บ first-steps
First Steps - FastAPI
Python 3.10+ from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} Copy that to a file main.py.
๐ŸŒ
Astral
docs.astral.sh โ€บ uv โ€บ guides โ€บ projects
Working on projects | uv
2 days ago - [project] name = "hello-world" version = "0.1.0" description = "Add your description here" readme = "README.md" authors = [ { name = "ferris", email = "[email protected]" } ] requires-python = ">=3.14" dependencies = [] [project.scripts] hello-world = "hello_world:main" [build-system] requires = ["uv_build>=0.12.0,<0.13"] build-backend = "uv_build" You'll use this file to specify dependencies, as well as details about the project such as its description or license.
๐ŸŒ
Medium
medium.com โ€บ @jameskabbes โ€บ adding-main-py-to-your-python-package-ff0cba4b8f98
Adding __main__.py to your Python package | by James Kabbes | Medium
September 21, 2023 - pip_file_counter/ โ”œโ”€ src/ โ”‚ โ”œโ”€ file_counter/ | | โ”œโ”€ __main__.py โ”‚ โ”‚ โ”œโ”€ utils.py ยท The __main__.py gives instructions for how to run your package as โ€œmainโ€. Test it out with a basic Python script.
๐ŸŒ
Great Learning
mygreatlearning.com โ€บ blog โ€บ it/software development โ€บ python main function and examples with code
Python Main Function and Examples with Code
May 31, 2023 - The characteristics of Python files are that they either act as reusable modules or as standalone programs. The if __name__ == "__main__" function can execute some code only when the Python file is run directly, and not when they are imported.
๐ŸŒ
Flask
flask.palletsprojects.com โ€บ en โ€บ stable โ€บ quickstart
Quickstart โ€” Flask Documentation (3.1.x)
To run the application, use the flask command or python -m flask. You need to tell the Flask where your application is with the --app option. $ flask --app hello run * Serving Flask app 'hello' * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) ... As a shortcut, if the file is named app.py or wsgi.py, you donโ€™t have to use --app.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ making-main-function-python
Defining a main function in Python - Python Morsels
September 27, 2021 - This version of our greet.py file can be run as a program to print out a random greeting: ... But if we import it as a module, it doesn't do anything (except give us access to functions and whatever else is in that module): ... It turns out there's a way to ask, are we being run from the command-line. Or put another way, is our current Python module the entry point to our Python process? This question can be asked using the statement __name__ == "__main__".