Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

There are a couple of methods that you can use:

  • First one as @david and @yarin_7 has mentioned you can stop calling the Area() function. Just because you declare it you don’t have to call it for the function to work.
  • Secondly, you could do the following:
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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading