1

I am confused about the below given code in Python where a function has been called before its definition. Is it possible? Is it because the function does not return a value?

from Circle import Circle def main(): myCircle = Circle() n = 5 printAreas(myCircle, n) #The function is called here def printAreas(c, times): xxxx xxxx main() 
4
  • 1
    What makes you think the function is called before its definition? Commented Mar 6, 2014 at 17:25
  • 2
    It is not. It is called when main is called, which is at the very end of the program. Commented Mar 6, 2014 at 17:26
  • Try to move the call to main before the definition of printAreas, as in: main()<NEWLINE>def printAreas(...): .... Commented Mar 6, 2014 at 17:28
  • See stackoverflow.com/questions/758188/… Commented Mar 6, 2014 at 17:29

3 Answers 3

3

What happens in your program:

  1. main is defined, with a reference to printAreas in its body—note, this is just a reference, not a call
  2. printAreas is defined
  3. main is invoked
  4. main calls printAreas.

So all is good—you are allowed to reference any names you want at any time you want, as long as you ensure these names will have been defined (bound to a value) by the time the code containing the reference is executed:

def foo(): print bar # reference to as-of-yet non-existent bar # calling foo here would be an error bar = 3 foo() # prints 3 
Sign up to request clarification or add additional context in comments.

Comments

0

Python will first parse your file, register all function, variables, etc into the global namespace. It will then call the main function, which will then call printAreas. At the time, both functions are in your script namespace, and hence perfectly accessible.

The thing that is confusing you is just the reading order.

Comments

0

You are calling main at the end of your program. This allows the interpreter to load up all your functions and then start your main function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.