Having difficulty in understanding python user-defined functions

Viewed 81

I am new to python. I searched on Google but didn't find an appropriate answer. What I am not understanding is, in the first program we can call bar function before its declared but in another program we can't call it before?

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

Output:

hello

Another code:

bar()
def bar():
     print("hello")

NameError: name 'bar' is not defined

4 Answers

In the first code, you have defined something that calls bar before bar itself has been defined, but it doesn't actually get called until after you have started executing foo, which happens after bar has ben defined.

You defined bar() after you called it. Instead, reverse the order:

def bar():
  print("hello")
bar()

In the first code snippet, though it appears that bar() is called before defining, it is actually not the case. bar() is called inside foo() and bar() is defined before calling foo(). Therefore, bar() is defined before calling it. In short, this is how it is actually being executed: define foo() -- define bar() -- call foo() -- call bar().

However, in the second code snippet, bar() is called before defining it.

Hope that clarifies.

Python reads your code from the top down. When you called bar(), it looked for where that was defined in the above code. It couldnt find it, so it threw an error. It is a good habit to define all of your functions first thing, so that python can always find them:

#functions
def foo():
   print("Hello foo")
def bar():
   print("Hello bar")
#end functions
foo()
bar()

Hopefully that was a clear explanation

Related