python-3.xfunction

How can I get Python to start executing from a specific line of code when the code is first run?


I've written the following python code:

def Area():

   print("Area() function has been called")
   return 

Area()       <----- This how I understood the definition of a function is to be done. I was not aware of this.

def mainProgram() :

   userSelection = -1
   while userSelection != 7 : 

   print ("CALCULATIONS MENU")
   print ("")
   print ("1) AREA (SQUARE)")
   print ("2) AREA (RECTANGLE)")
   print ("3) AREA (CIRCLE)")
   print ("4) PERIMITER (SQUARE)")
   print ("5) PERIMITER (RECTANGLE)")
   print ("6) PERIMITER (CIRCLE)")
   print ("7) EXIT")
   print ("")

   userSelection = int(input ("INPUT MENU CHOICE (1,2,3,4,5,6 OR 7)? "))

   if userSelection == 1 :
      Area()

   elif userSelection == 7:
     exit()

mainProgram()

And the output when the above script is executed in python is as follows:

Area() function has been called <---- This line gets outputed
CALCULATIONS MENU

1) AREA (SQUARE)
2) AREA (RECTANGLE)
3) AREA (CIRCLE)
4) PERIMITER (SQUARE)
5) PERIMITER (RECTANGLE)
6) PERIMITER (CIRCLE)
7) EXIT

INPUT MENU CHOICE (1,2,3,4,5,6 OR 7)? 

The program works fine but the problem is the following line gets executed before the mainProgram() gets executed. How can I change the code such that the body of the mainProgram() function gets executed first when the script is first run.

print("Area() function has been called")

Solution

  • There are a couple of methods that you can use:

    def Area():
        # body of the area function
    def mainProgram():
        # body of the mainProgram
    if __name__ == "__main__":
        mainProgram()
        Area()
    

    These are called dunders by the way just in case you wanna check them out