0

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    You can define a function almost anywhere in the code. But be sure to define it **before** you call it. – John Gordon Dec 18 '21 at 18:56
  • Have you tried it? It should be really easy to try. BTW, style is another consideration, but separate to functionality. – wjandrea Dec 18 '21 at 18:58
  • BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Dec 18 '21 at 18:58
  • You can even define functions inside functions, there are many use cases where that's a useful thing to do. – joanis Dec 18 '21 at 20:08

2 Answers2

0

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')
martineau
  • 119,623
  • 25
  • 170
  • 301
RNGHatesMe
  • 134
  • 7
0

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. See: Make function definition in a python file order independent

def foo():
   print("foo")

bar()

def bar():
   foo()

This would fail

MSH
  • 1,743
  • 2
  • 14
  • 22
  • why the second example still runs in which foo is declared after bar ? – Vageesh Dec 19 '21 at 11:46
  • It is about declaration before execution. You see in the second example we used `foo` inside the `bar`, and before using `bar` we declared the `foo`. Nothing was executed before it's declaration. – MSH Dec 20 '21 at 05:40