Main Blocks

A main block marks the code that should run when a file is used as a script.

This pattern looks strange at first. It solves a practical problem: the same file can be imported for its functions or run as a script.

__name__

Python gives every module a special name.

When a file is run directly, its __name__ is:

"__main__"

When the file is imported, its __name__ is the module name.

So this condition:

if __name__ == "__main__":

means:

only run this block when this file is the program entry point

Put the workflow in main

For small scripts, this is a clean shape:

The function count_words is reusable. The function main describes the script workflow.

A script-shaped program

Runs locally with Python in your browser.

Ready to run.

Why this matters later

As experiments grow, you will want code that can be:

  • run from the command line;
  • imported into another script;
  • tested one function at a time.

The main-block pattern keeps those uses separate.

Exercise: Entry-point condition

What condition is used in the standard Python main-block pattern?

Choose the condition

Select one choice, then check.

HintCompare the module name

Choose the line that compares Python's special __name__ value with "__main__".

SolutionUse the main guard

if __name__ == "__main__": detects direct script execution. def main(): defines a function, and main() calls it, but neither is the condition.