1

I just wanted to understand why you have to use if __name__ == '__main__': if we can run any python script even without using that statement. For example, I can run this script without using it:

def hello():
      print("hello")
      return 1234

# And here is the function being used
print(hello())
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
vkaul11
  • 4,098
  • 12
  • 47
  • 79

2 Answers2

5

It's done so that code is only executed when run as a script and not when you import the module.

jamylak
  • 128,818
  • 30
  • 231
  • 230
0

Code in the global namespace runs slightly slower. It's easy to make a main() function, so why not do it? It is optional though if you don't mind the module "running" when you import it

John La Rooy
  • 295,403
  • 53
  • 369
  • 502