
You’ve seen this weird block of code, often starting with “if name == main“, at the bottom of almost every professional Python script:
if __name__ == "__main__":
main()What is it? It’s a guard clause. It stops code from running when you don’t want it to.
The Two Ways to Run Code
There are two ways Python can execute a file:
- Directly: You type
python myscript.pyin the terminal. - Imported: Another script does
import myscript.
The Magic Variable: __name__
Python has a hidden variable called __name__.
- If you run a file directly, Python sets
__name__to the special string"__main__". - If you import a file, Python sets
__name__to the file’s actual name (e.g.,"myscript").
Why We Need It
Imagine you wrote a helpful library of maths functions, but at the bottom, you added some test code that prints “HELLO WORLD”. If someone imports your library to use the maths functions, they don’t want “HELLO WORLD” randomly printing in their terminal.
# my_math.py
def add(a, b):
return a + b
# WITHOUT the if-statement, this runs EVERY time it's imported!
print("Math library loaded!")
# WITH the if-statement, this ONLY runs if you run this specific file directly.
if __name__ == "__main__":
print("Running tests...")
print(add(2, 2))Always use this block for any code that executes actions (like running a game, starting a server, or testing functions).





