Functions in Python that Every Data Science Beginners should Begin Learning With

Nishtha Arora 23 Jun, 2021 • 6 min read

This article was published as a part of the Data Science Blogathon

Introduction

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.

Table of Contents

  • Functions
  • Built-in Functions
  • User-Defined Functions
  • Types of Arguments
    •  Positional Argument
    •  Default Argument
    •   Keywords Argument
    •  Variable-Length Argument
  • Recursive Functions
  • Conclusion

FUNCTIONS

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

Built-in 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

User-Defined Functions

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:-

  1. Function declaration(Header) – It consists of “def” keyword followed by the function name and curve parenthesis(). Inside the parenthesis, parameters are passed that can be used as a variable inside the function.
  2. Function Definition – It consists of function declaration along with the function body. The function body consists of a group of statements and each statement performs a particular task.
  3. Function Calling – This part of the function is used to call the function which begins the execution of the function. It consists of the function name and arguments that are enclosed in the parenthesis.
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
Functions Returning Values –

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.

The function calling statement changes in these functions. It stores the return value in some variable and then prints it on the screen or uses it later.

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

Types of arguments

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

Recursion

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-

  1. Terminating part – This part exits the control from the recursive function and returns values. It is also known as the base condition that terminates the function.
  2. Recursive part – This part executes again and again inside the function body. It usually consists of a function calling statement.

Working of recursive functions –

  1. Whenever a recursive call is taken for execution, the recursion part is not executed immediately. They are first pushed into the stack until the base condition is encountered. When the base condition is encountered, then the recursive calls are removed one by one from the stack and are evaluated until the stack is empty.

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

 Conclusion

So from the above article, we observe that Functions in Python play a very important role to minimize the length of the program and also increases the program readability, efficiency, and complexity. With the help of the divide and conquer approach, a large program is divided into smaller modules or functions. We also observe that functions can take as many parameters according to our needs and can be implemented in such a way that they perform a specific task. They can also return many values which can be used later.
Functions make our code reusable and along with that also save our time as the same functions can be imported in any other program to perform that same task. Also with the recursive category of the functions, we can reduce the length of our code by using the recursive calls but recursive functions are less efficient in space and time complexity as compared to normal functions.
The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.
Nishtha Arora 23 Jun 2021

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Python
Become a full stack data scientist
  • [tta_listen_btn class="listen"]