r/learnpython • u/pedrinjose • 9d 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/fallenreaper 9d ago
When a file is imported, the file is a script file so it executes top to bottom executing it all. If you want a file to run on its own you would use a main function which would essentially say "i want to run this file by itself" vs if you import it to make use of the functions without running some scripts.
Example:
def hello(name):print(f"Hello {name}")if __name__ == "__main__":hello("jake")You dont need it to execute the hello function if youre importing it, but if youre running the file itself you would.