Home > other >  Position of defining a function
Position of defining a function

Time:12-19

Is it necessary to define a function on the top of a code or can we define it in the middle also (i.e in the __main__ segment)? Like we define a function in the middle will it result in error during execution and flow of control?

CodePudding user response:

You can define a function in Python anywhere you want. However, it won't be defined, and therefore callable, until the function definition is executed.

If you're familiar with many other languages this feels odd, as it seems that most compilers/interpreters will identify functions anywhere in your code before execution and they will be available anywhere in your code. Python interpreters do not do that.

The following 2 code samples are both syntactically correct, but the second will fail because hello() isn't defined until after it is called:

Example 1 (works!):

def hello():
    print('Hello World')

hello()

Example 2 (fails! - name 'hello' is not defined):

hello()

def hello():
    print('Hello World')

CodePudding user response:

Just take a look to Python's definition.

Python is an interpreted high-level general-purpose programming language. (see: https://en.wikipedia.org/wiki/Python_(programming_language))

The interpreted is the key. We can think as if python executes the code line by line before checking the whole file. (It is a bad analogy, but for sake of this problem let's think it is true)

Now there can be many scenarios:

Running a function after declaration

foo()

def foo():
    print("foo")

This would fail

Running a function before declaration

def foo():
    print("foo")

foo()

this would succeed

Calling a function inside a function

def foo():
   print("foo")

def bar():
   foo()

bar()

or

def bar():
   foo()

def foo():
   print("foo")
bar()

These would succeed. Please notice in second example foo declared after bar. But still runs.

def foo():
   print("foo")

bar()

def bar():
   foo()

This would fail

  • Related