If __name__ == '__main__'

If __name__ == '__main__'

  • You are on the process of building a module with the basic math operations add, subtract, multiply, divide called basic operations saved in the basic_operations.py files.

Source Code:

def add(first_num, second_num):
    return first_num + second_num
def sub(first_num, second_num):
    return first_num - second_num
def mul(first_num, second_num):
    return first_num * second_num
def div(first_num, second_num):
    return first_num / second_num

print(add(18,16))
print(sub(45,23))
print(mul(15,12))
print(div(50,2)) 

  • When the module is imported our tests are displayed on the screen even though we didn't do anything besides importing basic_operations.
  • To fix that we use if __name__ == "__main__" in the basic_operations.py file like this.

Source Code:

def add(first_num, second_num):
    return first_num + second_num
def sub(first_num, second_num):
    return first_num - second_num
def mul(first_num, second_num):
    return first_num * second_num
def div(first_num, second_num):
    return first_num / second_num

if __name__ == "__main__":
    print(add(18,16))
    print(sub(45,23))
    print(mul(15,12))
    print(div(50,2)) 

  • Now that you know how to use the if __name__ == "__main__", let's understand how it works.
  • The condition tells when the interpreter is treating the code as a module or as program itself being executed directly .
  • Python has this native variable called __name__.
  • This variable represents the name of the module which is the name of the .py file.
  • Create a file my_program.py with the following and execute it.
  • print(__name__)



 

Comments