re: What's the use of if __name__ == '__main__': in Python? VIEW POST

re: Assume you have two scripts, and, and you want to import code from into If you don't add the if _...

Hey Luca. Thanks for taking the time to help me out.

Nice explanation.

It also indicates the starting point of the script when executing on its own.

I had actually thought of saying it like this, but then I doubted if it was really very correct since it kinda implies that it has to be there because it's the starting point of the execution. If I was a complete beginner, I'd take that to mean that a program without that part wouldn't run since the script doesn't have a starting point to execute from.

Here's what I mean. Consider this code for example:

def hello():


The code works just fine without the if __name__ == '__main__':. What's the starting point of the script when executing that code on its own?

Maybe I'm overthinking it? 😅


Hey Kinyanjui, you're absolutely right, the line does not have to be there.

If you want to use your script in two ways, execute it on its own and import it in another script, that's when you need to include if __name__ == '__main__':. Otherwise you don't need it.

code of conduct - report abuse