Function is collections of sequence and statement that are perform some task and operation. This is also called subroutine, method, procedure or routine in other programming language. The speciality of function is, it will be executes its instruction and statements when its called. define functions at once, and possible to use so many times.
In python are allowed to use two type of function. in-build (predefined) and another is custom (user defined) function. in this post we are learn about user defined function. define a function using this syntax.
Of this syntax, def is reserved word (keyword) that are used to define a function. after that is the name of function that are user defined. within parentheses define parameter. that are optional when function are no need any special data to operator on instruction.
In other case, there are possible to defined single or multiple parameters depends upon situations and operation. If using of multiple parameter to function then separate by comma (,) operator. let take one example.
#Basic overview of function """ Function Name: welcome Parameter List: none Description : simply to display message """ def welcome(): print("Welcome to python function") """ Function Name: version Parameter List: accepting a one argument Description : display given key value """ def version(key): print("Test version value :",key) """ Function Name: sum Parameter List: accepting two argument Description : Sum of given two numbers """ def sum(no1,no2): #add number result=no1+no2 print("Sum of (",no1 ,"+", no2,") is : ",result) #calling of functions welcome() version(1) #execute first time version(2) #execute second time sum(2,5) #execute first time sum(5.2,4.5) #execute second time
Welcome to python function Test version value : 1 Test version value : 2 Sum of ( 2 + 5 ) is : 7 Sum of ( 5.2 + 4.5 ) is : 9.7
similarly we can creates many number of function with many number of parameter. In this program there are defined three functions (welcome,version,sum). this are used to perform some operation. welcome function are display a message. and version function are accepting one parameter. this parameter value are display, when this function are called. Third function is sum() function. that are accepting two arguments(assume that this value are numbers). and perform operation of this number.
Function are executed when that are "call" by its name and associated value. In this example "welcome()" function are called once. and version and sum are execute two time. look at view its internal structure.
The name of function is internally used as function object. so that is defined the scope and accessibility of function. note that in above image are every function object are related to associative function.
Important point about python function
1) Naming convention: the name of function by user define, can't use keywords on this place. this name is an identifier. this will start of underscore and alphabets. and cannot separate by spaces (white character). for example
# valid function naming convention def config(): print("config function") def getSalary(id): print("getSalary function") def __setSalary(id,amount): print("__setSalary function") # similar way
Most of programmers separate name of function by using of underscore and camelcase. because compared to normal text that much readable and formatted. for example.
#case 1 (camel case) def accountBlance(): #statements def studentRecord(id): #statements def studentMarks(): #statements def getSalary(employeeKey) #statements #Case 2 (underscore) def account_blance(): #statements def student_record(id): #statements def student_marks(): #statements def get_salary(employee_key) #statements
Note that this is for more readable for human been.
2) Statements : Python function should be defined at least one instruction and statement. otherwise it will produce an error.
#define a function def accountBlance(): #statement required #function calling accountBlance()
File "test.py", line 6 accountBlance() ^ IndentationError: expected an indented block
So avoiding this situation giving a one instruction inside function. otherwise use pass statement. for example
#define a function def accountBlance(): #pass statement pass #function calling accountBlance()
3) Passing parameter: parameter of argument is define, how many number of arguments accepted by function. normally this parameter are accepting value and instance of objects.
4) default parameter: default parameter are useful to set initial value of function parameter. default argument are set from right to left. for example.
#define a function # value3 is default parameter def message(value1,value2,value3=90): #display parameter values print(value1,value2,value3) message(1,2)
(1, 2, 90)
5) return statement: When function is returning any value, there is use of return statements.
6) function calling: Function calling is a process to start execution of specific function.
7) function recurion: function calling is provide an availability to use recursion. this is an contiguous function calling process to achieve desired output of a specified condition. this is most useful technique there can be used to solve complex problem in very efficiently. let take one example for recursion.
#calculating factorial of given number def factorial(num): #base condtion to stop excution if(num==0) : return 1 #Recursive call factorial function return factorial(num-1)*num number=5 #Given a value result=factorial(number) #call factorial function print("Factorial of ",number, " is :",result)
Factorial of 5 is : 120
In this program are calculate factorial of given number using recursive approach. this is simple example of recursion. given number is five and this program are calculate factorial of five. factorial() function is executing 6 times.
base condition (num==0) of this program are stop the execution. after that returning the calculated result.
look at view this image when sum==0 then this function is returning value 1 to previously executed function. after then this function scope are over . and control are back to previous executed function.
previous function result is one and in this local variable of num is also one. then resultant of this function (1*num)=1. so this function are also returning result 1. and control are back to previous executed function. after of this
Previous function result is one and in this local variable of num is two. then resultant of this function (1*num)=2. so this function are also returning result 2. and control are back to previous executed function. after of this.
Previous function result is 2 and in this local variable of num is 3. then resultant of this function (2*3)=6. so this function are also returning result 6. and control are back to previous executed function. after of this.
Previous function result is 6 and in this local variable of num is 4. then resultant of this function (6*4)=24. so this function are also returning result 24. and control are back to previous executed function. after of this.
Previous function result is 24 and in this local variable of num is 5. then resultant of this function (24*5)=120. so this function are also returning result 120. and control are back to previous executed function. after of this finally get actual result.
Recursion are used to solve most data structure problem in this example we are try to explained basic concepts of calculate factorial of given number. here skipped initial function call process. because when call new function always created new memory. this memory are store the local variables. I hope you are understand the concept of function calling process.
8) Nested (Inner) function : Nested function means that are defined one function inside another function. there are used normally in some special cases. define inner function are used only within the defined function. that is not accessible to out of this scope. so this inner function are completely protected.
#Nested function example #define a function def outerFun(): auxiliary=100 #define a inner function def innerFun(): auxiliary=200 #local variable print("innerFun : " ,auxiliary) #display value innerFun() #call inner function print("outerFun : " ,auxiliary) #display value outerFun()#call normal outer function
('innerFun : ', 200) ('outerFun : ', 100)
In this program outerFun() and its innerFunc() are has local variable. innerFun() are accessible within the only outerFun(). see this image.
Note that when executed outer function . then visible the scope of inner function. see another example.
#define a function def outerFun(): auxiliary=100 #define a inner function def innerFun(): auxiliary=200 #local variable print("innerFun : " ,auxiliary) #display value innerFun() #call inner function print("outerFun : " ,auxiliary) #display value innerFun() #call inner function outerFun()#call normal outer function
Traceback (most recent call last): File "test.py", line 15, in <module> innerFun() #call inner function NameError: name 'innerFun' is not defined
So note that this inner function are not accessible outside defined function
Default Value of function
Default value of function are assigned from right to left in function arguments in all modern programming. python is also supported to set default value on parameter. for example.
def checkOut(info=12): #set default value print(info) checkOut() checkOut()
In this example provided the default value 12 of checkOut info variable. when call of this function and not pass info parameter value then this default value is assign on variable(object).
In this case assigned a simple value to parameter. but assume that if default value is an list so that is very interesting. when modified default list value at any time of function calling execution. that default value is replaced by current modified list . see this example.
In this scenario checkOut function is execute first time and inside a function that are add one list item, and info variable (object) is hold reference of default list. that the reason, defaul list value is update.
So what are happening when Calling this function in next time. view of this image.
that is same as previous function calling but in this time list is not empty that is contain one element. and after that add one more new element. after that resultant of list element is [1,2].
Above of program checkOut() function is execute 5 times. so after execute 5 times list contain following elements.
Final conclusions are, default value of function is assigned when it's defined. and if list, dictionary, instances of class are exist in default parameter. when modified its value that is reflected on its refrance.
when more than one parameter default value then in this case we can pass value using of function arguments names. see this example.
def fruits(test1="Mango",test2="Oranges",test3="Apple"): print("test1 : ",test1) print("test2 : ",test2) print("test3 : ",test3) print("Test case 1") fruits() #no arguments print("\nTest case 2") #replace parameter by given values fruits("blackberry","banana","watermelon") print("\nTest case 3") #set parameter value by associate parameter name fruits(test2="grapes",test1="Oranges",test3="strawberry")
Test case 1 test1 : Mango test2 : Oranges test3 : Apple Test case 2 test1 : blackberry test2 : banana test3 : watermelon Test case 3 test1 : Oranges test2 : grapes test3 : strawberry