Newbie here. A very beginner question but would like your help

Can anyone help me with this code please.

if __name__ == '__main__':
    print("Hello, World!")

What is the function of the double underscores and the meaning of the first line with “if” and why does it even work?

In short: it allows the code to execute when the file runs as a script, but not when it’s imported as a module.

For the most part, it’s not needed and it’s certainly not needed for those who are just starting out with Python: first, learn the fundamentals, then move on to more advanced topics.

1 Like

Thankyou, for the reply. I started with with Easy and Solved an this was the first problem. I went through the internet and quite a few people said hackerrank was the way to go to start python.

You’re welcome.

I’d like to refer you to my comment here:


Double underscores as part of the name of variables and method (so called “dunder” methods) signify variables and methods that mean something special to the interpreter and may be defined for you.

In this case, __name__ gets set to the name of the module when it is imported as a library, but is set to "__main__" when you run the file as a program. So this statement will execute what is inside the if only if you run the file as a program, not if you use it as a library module.

As Rob wrote, advanced feature.


Rob’s answer is great.
If you want to know something more.
You can read this manual

the __name__ is actual globals()['__name__']

you can


see what happend

1 Like


1 Like