In any complex program, it’s crucial to organize the code properly: define a starting point and separate its logical components.
In Python, modules can be executed on their own or imported into other modules, so a well‑designed program must detect the execution context and adjust its behavior accordingly.
Separating run‑time code from import‑time code prevents premature execution, and having a single entry point makes it easier to configure launch parameters, pass command‑line arguments, and set up tests. When all important logic is gathered in one place, adding automated tests and rolling out new features becomes much more convenient.
For exactly these reasons it is common in Python to create a dedicated function that is called only when the script is run directly. Thanks to it, the code stays clean, modular, and controllable. That function, usually named main()
, is the focus of this article.
All examples were executed with Python 3.10.12 on a Hostman cloud server running Ubuntu 22.04.
Each script was placed in a separate .py
file (e.g., script.py
) and started with:
python script.py
The scripts are written so they can be run just as easily in any online Python compiler for quick demonstrations.
The simplest Python code might look like:
print("Hello, world!") # direct execution
Or a script might execute statements in sequence at file level:
print("Hello, world!") # action #1
print("How are you, world?") # action #2
print("Good‑bye, world...") # action #3
That trivial arrangement works only for the simplest scripts. As a program grows, the logic quickly becomes tangled and demands re‑organization:
# function containing the program’s main logic (entry point)
def main():
print("Hello, world!")
# launch the main logic
if __name__ == "__main__":
main() # call the function with the main logic
With more actions the code might look like:
def main():
print("Hello, world!")
print("How are you, world?")
print("Good‑bye, world...")
if __name__ == "__main__":
main()
This implementation has several important aspects, discussed below.
The core program logic lives inside a separate function. Although the name can be anything, developers usually choose main, mirroring C, C++, Java, and other languages.
Both helper code and the main logic are encapsulated: nothing sits “naked” at file scope.
# greeting helper
def greet(name):
print(f"Hello, {name}!")
# program logic
def main():
name = input("Enter your name: ")
greet(name)
# launch the program
if __name__ == "__main__":
main()
Thus main()
acts as the entry point just as in many other languages.
Before calling main()
comes the somewhat odd construct if __name__ == "__main__":
.
Its purpose is to split running from importing logic:
If the script runs directly, the code inside the if block executes.
If the script is imported, the block is skipped.
Inside that block, you can put any code—not only the main()
call:
if __name__ == "__main__":
print("Any code can live here, not only main()")
__name__
is one of Python’s built‑in “dunder” (double‑underscore) variables, often called magic or special. All dunder objects are defined and used internally by Python, but regular users can read them too.
Depending on the context, __name__
holds:
"__main__"
when the module runs as a standalone script.
The module’s own name when it is imported elsewhere.
This lets a module discover its execution context.
Helper functions and classes, as well as the main function, are wrapped separately, making them easy to find and read. Global code is minimal—only initialization stays at file scope:
def process_data(data):
return [d * 2 for d in data]
def main():
raw = [1, 2, 3, 4]
result = process_data(raw)
print("Result:", result)
if __name__ == "__main__":
main()
A consistent style means no data manipulation happens at the file level. Even in a large script you can quickly locate the start of execution and any auxiliary sections.
When code is written directly at the module level, every temporary variable, file handle, or connection lives in the global namespace, which can be painful for debugging and testing. Importing such a module pollutes the importer’s globals:
# executes immediately on import
values = [2, 4, 6]
doubles = []
for v in values:
doubles.append(v * 2)
print("Doubled values:", doubles)
With main()
everything is local; when the function returns, its variables vanish:
def double_list(items):
return [x * 2 for x in items] # create a new list with doubled elements
def main():
values = [2, 4, 6]
result = double_list(values)
print("Doubled values:", result)
if __name__ == "__main__":
main()
That’s invaluable for unit testing, where you might run specific functions (including main()
) without triggering the whole program.
Without the __name__
check, top‑level code runs even on import—usually undesirable and potentially harmful.
some.py:
print("This code will execute even on import!")
def useful_function():
return 42
main.py:
import some
print("The logic of the imported module executed itself...")
Console:
This code will execute even on import!
The logic of the imported module executed itself...
The safer some.py
:
def useful_function():
return 42
def main():
print("This code will not run on import")
main()
plus the __name__
check guard against accidental execution. Inside main()
you can also verify user permissions or environment variables.
Remember: main()
is not a language construct, just a regular function promoted to “entry point.” To ensure it runs only when the script starts directly:
main()
in the desired order.if __name__ == "__main__"
guard. This template yields structured, import‑safe, test‑friendly code—excellent practice for any sizable Python project.
# import the standard counter
from collections import Counter
# runs no matter how the program starts
print("The text‑analysis program is active")
# text‑analysis helper
def analyze_text(text):
words = text.split() # split text into words
total = len(words) # total word count
unique = len(set(words)) # unique word count
avg_len = sum(len(w) for w in words) / total if total else 0
freq = Counter(words) # build frequency counter
top3 = freq.most_common(3) # top three words
return {
'total': total,
'unique': unique,
'avg_len': avg_len,
'top3': top3
}
# program’s main logic
def main():
print("Enter text (multiple lines). Press Enter on an empty line to finish:")
lines = []
while True:
line = input()
if not line:
break
lines.append(line)
text = ' '.join(lines)
stats = analyze_text(text)
print(f"\nTotal number of words: {stats['total']}")
print(f"Unique words: {stats['unique']}")
print(f"Average word length: {stats['avg_len']:.2f}")
print("Top‑3 most frequent words:")
for word, count in stats['top3']:
print(f" {word!r}: {count} time(s)")
# launch program
if __name__ == "__main__":
main()
Running the script prints a prompt:
Enter text (multiple lines). Press Enter on an empty line to finish:
Input first line:
Star cruiser Orion glided silently through the darkness of intergalactic space.
Second line:
Signals of unknown life‑forms flashed on the onboard sensors where the nebula glowed with a phosphorescent light.
Third line:
The cruiser checked the sensors, then the cruiser activated the defense system, and the cruiser returned to its course.
Console output:
The text‑analysis program is active
Total number of words: 47
Unique words: 37
Average word length: 5.68
Top‑3 most frequent words:
'the': 7 time(s)
'cruiser': 4 time(s)
'of': 2 time(s)
If you import this program (file program.py
) elsewhere:
import program # importing program.py
Only the code outside main()
runs:
The text‑analysis program is active
So, a moderately complex text‑analysis utility achieves clear logic separation and context detection.
Use main()
(almost always appropriate) when:
You can skip main()
when:
In short, if your Python program is a standalone utility or app with multiple processing stages, command‑line arguments, and external resources—introduce main().
If it’s a small throw‑away script, omitting main()
keeps things concise.
The main()
function in Python serves two critical purposes:
Isolates the program’s core logic from the global namespace.
Separates standalone‑execution logic from import logic.
Thus, a Python file evolves from a straightforward script of sequential actions into a fully‑fledged program with an entry point, encapsulated logic, and the ability to detect its runtime environment.