This article was published as a part of the Data Science Blogathon
Python is an interpreted high-level language that supports a large range of variables, operators, input/output statements to carry out various tasks like adding two numbers, making a calculator, etc. Python also supports various data types like lists, tuples, strings, dictionaries, etc. It is quite easy to write the small codes in the python program but this task becomes difficult when the size of our code increases. Also, it is difficult to keep track of large programs and it also increases the complexity of the code.
To overcome this issue, python provides a special feature known as Functions. With the help of this feature, we can divide our large program into smaller modules known as function. These functions are independent of each other.
In this article, we are going to study the concepts of functions that how they are implemented and used in python to make the task easier.
Functions are a group of statements that are used to perform some specific task. It is a systematic process that decomposes a large program into smaller modules that are capable of executing independently. This approach is known as the modular approach or step-wise refinement approach. These functions can also be imported into any other program to perform that specific task.
Advantages of functions –
1) Re-usability of code
2) Easy to understand the code
3) Reduces the time complexity
Types of functions –
Python provides two types of functions:-
1) Built-in functions
2) User-defined functions
Those functions that are already defined in python programming are known as built-in functions. They can be directly called in the programs and they make our task much easier. Some common built-in functions are:-
1) input() – This function is used to accept any value from the user. By default, this function stores the value entered by the user in character data type.
name=input("Enter youy favourite Programming Langauge") print("My favourite programming langauge:-",name) print(type(name)) Enter youy favourite Programming Langauge python My favourite programming langauge:- python <class 'str'>
2) Type-conversions functions – These functions are used to convert the value from one data type to another data type. Some of these functions are:-
a) int () – It converts the value into an integer data type.
b)float() – It converts the value into float data type.
c) str() – It converts the value into a string data type
>>>varibale = 123
>>>type(varibale
<class 'int'>
>>> float(varibale)
123.0
>>> str(varibale)
'123'
>>> int(varibale)
123
3) len() – this function calculates the length of the elements present in the list, tuples, dictionary, etc.
>>> list1=[14,23,45,67] >>> len(list1) 4 >>> str1="analytics" >>> len(str1) 9
These functions are created by the user according to their needs. User-defined functions improve the readability and clarity of a program. It also reduces code duplication.
User-Defined functions are created with the “def” keyword and they consist of three parts:-
Syntax:- def function_name(parameters): #function header statement 1 Statement2 -------- function_name(arguments) #function calling
def addition(num1, num2): # Function header num3= num1 + num2 print("The sum of two numbers-",num3) addition(4,5) #function calling The sum of two numbers- 9
Some User-Defined functions return one or more value from the functions. Whenever a return statement is encountered in the functions, the control of the programs exits the function body and returns the value. The major advantage of the return value is that it can be stored in the variable and used later in the program.
Syntax –
Var_name = function_name(arguments)
def addition(num1, num2): # Function header num3= num1 + num2 return num3 answer=addition(4.5,5) #function calling print("The sum of two numbers-",answer) The sum of two numbers- 9.5
There are four types of arguments are available that can be used to call the functions.
1) Positional Arguments – These arguments are passed to a function in a correct position order that is in the same order they are present in the function header.
def simple_interest(principal,time,rate): interest=(principal * time * rate)/100 amount = interest + principal return interest, amount intr,amnt= simple_interest(4500,3,1.2) print("The interest:- ",intr) print("The amount:- ",amnt) The interest:- 162.0 The amount:- 4662.0
2) Default Arguments – Sometimes in the function header some parameters have a default value that can be used only if the value for that parameter is not passed in the function calling statement. One important point to be noted in the default argument is that all the. Default parameters must be present after the non-default parameters in the function header otherwise it will give an error.
def simple_interest(principal,time,rate=2): interest=(principal * time * rate)/100 amount = interest + principal return interest, amount intr,amnt= simple_interest(4500,2) print("With Default value of Rate") print("The interest:- ",intr) print("The amount:- ",amnt) intr,amnt= simple_interest(4500,2,4) print("With Passing new value of Rate") print("The interest:- ",intr) print("The amount:- ",amnt) With Default value of Rate The interest:- 180.0 The amount:- 4680.0 With Passing new value of Rate The interest:- 360.0 The amount:- 4860.0
3) Keywords Arguments – sometimes the function headers contain many parameters and it becomes difficult to remember the arguments order wise but it is quite easy to remember the name of the parameters. In this case, we will use keywords arguments, in the calling functions we can use the exact name of the parameters to call the function and it need not be in the same order as that in the function header.
def simple_interest(principal,time,rate): interest=(principal * time * rate)/100 amount = interest + principal return interest, amount intr,amnt= simple_interest(rate=5,principal=2000,time=1) print("The interest:- ",intr) print("The amount:- ",amnt) The interest:- 100.0 The amount:- 2100.0
4) Variable-length arguments – This type of argument allows us to pass any length of argument in the calling statement of the function according to our needs so there is no need to mention a fixed number of parameters in the function header.
def summation(*n): total=0 for i in n: total+=i print("Total=",total) summation(7) summation(6,8) summation(5,6,7,7) summation(2,3,4,6,7) Total= 7 Total= 14 Total= 25 Total= 22
In some of the programs some lines of code have to execute again and again or in other cases some of the programs need a value generated by the function in the first execution into the second execution and so on. In such cases, a lot of variables must be needed to keep the track of all the values generation in each compilation. So to resolve this issue and make this task easier we have a most popular type of function in Python called Recursive functions.
Recursive functions or Recursion is defined as a capability of any function in which a function can call itself again and again from its own body.
The recursive function consists of two parts-
Working of recursive functions –
2. Each time a recursive call is made, new memory is allocated to the variable used by the function.
#recursive function to calculate the power of the number
def rec_power(x,num): if num==0: return 1 else: return x*rec_power(x,num-1) base=4 power=2 print(base,"to the power",power,":-") print(rec_power(base,power)) 4 to the power 2 :- 16
#Fibonacci Series using Recursion
def rec_fibonacci(n): if n<= 1: return n else: return(rec_fibonacci(n-1)+ rec_fibonacci(n-2)) nterms= int(input("Enter the number of terms you want in Fibonacci Series")) print("Fibonacci Serires:-") for i in range(nterms): print(rec_fibonacci(i)) Enter the number of terms you want in Fibonacci Series 10 Fibonacci Serires:- 0 1 1 2 3 5 8 13 21 34