Lazo Lab Sign up

Python Projects & Skills / Working like a pro

Lesson 4 of 28

The main guard

if __name__ == "__main__": lets a file run code only when it's run directly, not when another file imports it.

Key points

  • Put your start-up code under it
  • Lets files be both scripts and modules
  • Very common in real projects
def main():
    print("Running")

if __name__ == "__main__":
    main()
Watch a video on thisOpens YouTube search results for “The main guard” in a new tab

Quiz · +10 XP

When does code under if __name__ == "__main__" run?

Log in to save progress and earn XP.