Syntax

Python Main Guard Syntax

In Python, main guard: runs code only when the file is run directly — if __name__ == "__main__":

Quick Answer

Syntax
if __name__ == "__main__":
PythonSyntax

Main Guard

Code example
if __name__ == "__main__":

Runs code only when the file is run directly.

Learn More

How to main guard in Python

  1. Open your Python file or editor.
  2. Copy the example, then replace its sample names and values for your code.

Python Main Guard Syntax

Use if __name__ == "__main__":.

Related Syntax References

Frequently asked questions

What is the Python syntax for main guard?

Use this pattern: if __name__ == "__main__":

Can I copy this Python code example?

Yes. Use Copy code and adapt the example to your program.

Is this Python syntax different on Mac or Windows?

No. The language syntax is the same across operating systems.

Official source · How we verify