r/learnpython • u/pedrinjose • 7d ago
Basically, if main
In Python, when you run your program in another folder, we add this, but I don't understand why. What's the point of doing this? If someone could explain it in a simplified way, I'd appreciate it.
10
Upvotes
View all comments
1
u/FatDog69 7d ago
You often start by writing 1 python script and the code starts running after "if __name__..".
Later you are doing other scripts but find yourself wanting to copy code/functions from your earlier scripts.
If your old script was "comic_rename.py" you could "IMPORT comic_rename" and suddenly all your methods and functions in "comic_rename" are available to your new script.
But this only works if every script you write includes the "if __name__" type of logic.
It also helps if you write all your scripts as object oriented with functions that don't assume too much or try to do too much in 1 call. This takes time & experience before you learn this.