PYTHON PROGRAM TO CALL METHODS FROM MAIN()

Introduction:

In python programming the main function is used to define or indicate the starting point or the execution point of the program. python language do not have an explicit main function like c or java. but this can be implemented by using the special statement. this is done to organize the code and make it more readable and maintainable.

let us look into a very simple example:

def main():
   print("hi coders")
if __name__="__main__":
   main()

In the above function the main function contains the code that runs when the program is executed, whereas the if statement if the code is being run directly or imported as a module in any other script. if the condition inside the if statement is true then it calls the main function.

why should we use a main()?

  • organizes the code
  • improves readability
  • makes testing easier
    def start():
       print("hi, welcome to the program")
    def addition(a,b):
       return a + b
    def subtract(a,b):
       return a - b
    def main():
       num1 = 10
       num2 = 7
       sum_result = add(num1, num2)
       print (" the result is: {sum_result}")
       sub_result = subtract(num2 ,num1)
       print ("the result is: {sub_result}")
    if __name__ == "__main__":
       main()

    Here in this program the start() functions prints the first message given. Then we have created two functions namely addition and subtract the addition function adds the two numbers given in the program like num1 and num2 and the subtract function subtracts the two numbers given in the program. These are the two functions that are defined in the program . Finally the main function calls the addition and subtract functions and execute them and print the result respectively.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top