Basic functions flow:
- We define function in python using “def”
- Function can have n number of statements
- Function execute only when we call that function.
- Calling is a single statement used to access the function logic
def fun():
print("Hello...")
return
fun() # calling
- We cannot call a function before it has defined.
- Python is interpreted programming language, hence the code execute line by line from top to bottom.
- We cannot call the function before it is ready(not defined)
fun() # error :
def fun():
print("Hello...")
return
- The main advantage of functions is code re-usability.
- We can call the function many times once we defined.
def test():
print("logic..")
return
test()
test()
test()
- One source file(.py file) can have more than one function definition.
- Functions get executed in the order we invoke.
def m1():
print("m1.....")
return
def m2():
print("m2.....")
return
m2()
m1()
We can access one function from another function.
def m1():
print("control in m1...")
return
def m2():
print("control in m2...")
m1() #calling
print("control back to m2 from m1...")
return
print("Program starts...")
m2() #calling
print("Program ends...")
Check the program execution:
print(1)
def test():
print(3)
return
print(2)
test()
print(4)
Output it:
print(7)
def m1():
print(3)
return
print(6)
def m2():
print(2)
return
print(9)
m2()
print(4)
m1()
print(0)
Output it:
def m1():
print(2)
return
print(7)
m1()
print(4)
def m2():
print(2)
m1()
print(8)
return
print(9)
m2()
print(6)