⬅ Previous Topic
Python Functions with ParametersNext Topic ⮕
Python Lambda Functions⬅ Previous Topic
Python Functions with ParametersNext Topic ⮕
Python Lambda FunctionsUnlike many other programming languages, Python doesn't require a main function to start execution. That might sound liberating at first—but it also means structure is your responsibility.
This tutorial will help you understand how and why to use a main()
function in Python. Whether you’re writing a script or building a module, learning to organize your code using main()
and __name__ == "__main__"
is a fundamental skill.
Python executes code from top to bottom. If you don’t take care, everything in your script might run immediately when imported elsewhere. To avoid this, we use a main guard pattern:
def main():
print("Hello from main function!")
if __name__ == "__main__":
main()
__name__ == "__main__"
Python assigns a special variable called __name__
to every module. When a script is run directly, __name__
is set to "__main__"
. But if the same script is imported, __name__
becomes the module's name.
# file: greet.py
print("This is always printed")
def hello():
print("Hello!")
if __name__ == "__main__":
print("This runs only when executed directly")
import greet
This is always printed
Notice how "This runs only when executed directly"
did NOT appear? That’s the power of __name__ == "__main__"
—it guards what should only run in standalone mode.
Create a main()
function that wraps the core logic of your script.
def main():
print("Starting the program")
# Add your core logic here
Right at the bottom of your file, add the guard to control script behavior:
if __name__ == "__main__":
main()
Save your script as my_script.py
and run it using:
python my_script.py
Starting the program
main()
.__name__ == "__main__"
, your code may run unexpectedly during import.main()
before defining it or outside the guard can lead to issues.main
.For more complex scripts, you might want to pass command-line arguments using sys.argv
:
import sys
def main():
print("Arguments passed:", sys.argv)
if __name__ == "__main__":
main()
Arguments passed: ['my_script.py', 'arg1', 'arg2']
This gives you flexibility for CLI-based utilities.
While Python doesn’t enforce a main()
function like C or Java, learning to use it adds clarity, safety, and professionalism to your scripts. It’s one of those “small things” that sets experienced Python developers apart.
Always ask yourself: Could this code be imported in the future? If yes, then guard it well.
Now that you’ve understood how main()
works, try modifying a few of your older scripts. See the difference it makes in readability and modularity.
⬅ Previous Topic
Python Functions with ParametersNext Topic ⮕
Python Lambda FunctionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.