Back
+15 XP
Concept

The `if __name__ == '__main__':` Idiom

When run directly as a script, `__name__` is `'__main__'`. When imported as a module by another file, `__name__` matches the file's module name.

python
def main():
    print("Executing standalone task...")

if __name__ == "__main__":
    main()

# 13. The `if __name__ == '__main__':` Idiom When run directly as a script, `__name__` is `'__main__'`. When imported as a module by another file, `__name__` matches the file's module name: ```python def main(): print("Executing standalone task...") if __name__ == "__main__": main() ``` Without this check, any code sitting at top-level executes immediately the millisecond someone imports your file. Guarding execution with `__name__ == '__main__'` allows code to be both runnable and reusable.

Checkpoint

What is `__name__` set to when a file is imported via `import my_script`?

Practice

Write a script with a function `run()` that prints `"System active"`. Call it inside `if __name__ == "__main__":`.

Terminal
01
Tap code blocks below to assemble
Available Blocks