Introduction to Python Functions for Data Science Beginners
This article was published as a part of the Data Science Blogathon.
Python is a truly wonderful programming language. Python’s flexibility has made it the most widely used programming language in the data science domain.
But it can be difficult to grasp for beginners, especially those who don’t have a programming background. One of the most complex concepts to grasp – Python functions.
A function is a logically grouped set of statements that perform a specific task. We require the functions to avoid the group of same codes again and again, as the length of the code will increase, the reusability will also go down.
In essence, the biggest advantage of a Python function is code reusability.
Here are a few other advantages of using Python functions:
- Avoid repetition of codes
- Increases program readability
- Divide a complex problem into simpler ones
- Reduces chances of error
- Modifying a program becomes easier by using a function
So when we learn machine learning and data science, we will come to know that the algorithms which we are using are nothing but the functions. And in this article, we’ll learn about the basics of Python functions and how to use them.
Table of Contents
- Types of Python Functions
- Functions Parameters
- Return Statement
- Types of Variables
- Recursive Functions
- Lambda Functions
- Filter() Function
- Map() Function
- Reduce() Function
Types of Python Functions
There are two types of functions in Python.
1. Built-in Functions or pre-defined functions
These are the functions which are already defined by Python. For example: id () , type(), print (), etc.
2. User-Defined Functions or Customized Functions
These are functions that are defined by the users for simplicity and to avoid repetition of code.
The syntax for defining a function is:
Def function_name (Parameter) : “ Doc String “ Body Return value
Here, the def keyword is mandatory, and the return is optional. Here’s an example:
Def wish() : print(“Hello Good Evening”)
So we can now call it:
Every time we do it, “Hello Good Evening” will be printed.
Python Function Parameters
Let us understand this with a simple example.
Write a function to take the name of the student as input and print a wish message by name. So here, one thing is clear – it is mandatory to give the parameter inside the ().
Def wish(name): Print (“Hello” , name, “Good Evening”)
Now, if the function is having the argument or parameter, we cannot call it wish(), as we will get the type error.
Here, we need to provide the value, so we can simply call it like:
Python Return Statement
A function can return some value. So, by the logic we provide, we will get some result, and that result is the return.
Def add(a,b) : sum=a+b Return sum add(10,20)
We have not asked the return value sum, but Python will not give an error since it is not compulsory to take the return value.
However, we will not get any value as we have not called the return function. Here, we can execute it like we have returned the value and hold it in a variable, and then print the output:
Result =add(10, 20) Print (Result)
Or we could have done this:
There’s one more scenario. Let’s say we made one function:
Def f1() : Print (“Hello”) x=f1() print(“The return value is “ ,x)
Now the thing is we have not returned any value in the code, so we could hold the value in x because we do this when we return some value.
Keep in mind that Python returns the value None by default.
One more thing, the return statement we have discussed is optional but if we want to store the value and use it again outside of the function, then we can use the return function.
Returning Multiple Values from the Functions
A Python function can return multiple values.
Def sum_sub(a,b) : Sum =a+b Sub = a-b Return sum, sub
So to execute this code, we should type it as:
x, y = sum_sub(20, 10) Print (The sum is , x) Print (The subtraction is , y)
Arguments in Python
There are several types of arguments in Python. Let’s see and understand what arguments are.
Let us understand this with the help of an example:
Def sub(a,b) : print(a-b) sub(200,100)
Here, a = 200 and b = 100. We know this since we have assigned those positions. So in a positional argument, the order is important. As we change the order, the result will also change.
Also, the number of arguments should also be the same.
Def sub (a,b) : print(a-b) sub(200,100) sub(a=200 , b=100)
Here, we are giving the values through variables, so positioning will not matter. But yes, the number of arguments are important here as well.
These are the arguments which are applied when we have actually defined the argument, but have not passed it.
So let us understand this:
Def identity(name) : Print(“Hello your name is”, name) identity()
This will give a positional error, as we have defined the argument, but we have not passed the argument. If we need to avoid this, we can do it like:
Def identity(name=”Guest”) : Print(“Hello your name is”, name) identity()
Now it will execute and will take the Guest as the default.
Variable Length Arguments
It can take any number of arguments:
*-> n variable length argument
It can have 0 arguments as well. We can have variable length arguments like:
Def f1(*n): print(“Variable length argument”) f1() f1(10) f2(10,20,30)
Internally they all are saved as tuples so we can access them.
Just to summarize, we can use both positional arguments as well keyword arguments simultaneously. But first, we have to take the positional argument and only then we can take keyword arguments.
Default vs Non Default arguments
If we are not passing any value, then only the default value will be considered. After default arguments, we should not take non-default arguments, i.e. default arguments should be the last arguments.
Types of Variables
There are two types of variables: Global Variables and Local Variables.
Global variables are always outside the function and can be access by all the functions whereas local variables are defined in the particular functions.
In Python, we can have the global as well local variable as the same name.
Let us see with the help of an example, and we’ll take the example by taking one function under the other function.
a=10 # global variable Def f1() : a=20 # local variable print(a) f2(): print(a)
So if we put the output as:
Then simply we needed to understand in the first case i.e in f1 function a =20 , so the output will be 20, irrespective of the global variable. While in f2 the output will be 10, as there is no local variable defined in f2, so it will take the value of the global variable.
But now, let’s say we want that f1 function value “a” remains global, so we need to explicitly put a global keyword:
a=10 Def f1() : Global a a=20 print(a) f2(): print(a)
Now the output will be 20 for both, as the global value has been changed to 20 when we defined it explicitly.
As the name suggests, it is the function that calls itself. We can write concise code that can help in solving complex problems. Here’s an example:
Def factorial (n) : If n==0: result=1 Else: Result =n* factorial(n-1) Return result
* The maximum recursion depth is 995 times it can call the same function.
These are the functions without having a name or can be known as no name function or anonymous function. They are generally used for instant use or one time usage, and are not required to be used again.
Lambda input argument : expression
So for figuring out the square of a number:
Lambda n: n*n
Here’s a quick example:
s=lambda a,b:a+b print(s(2,4))
Shorter Code by Using the filter () Functions
Filter (function, sequence)
Here, one argument is the function itself in filter functions.
Let’s say we want to have one list from 0 to 10 to have even numbers. Now, our filter function format is:
The Function argument used in the filter function is used to verify the if the condition is true or not. If it is true, then it will print the sequence arguments, and if it is false, it won’t be printing that.
l=[0, 1, 2, 3, 4, 5, 6, 7,8,9,10] Def iseven(n): If n%2==0: Return True: Else: Return False l1=filter(iseven, l)
But one thing we need to change – by default, the return type of filter is filter object, so we need to typecast it into the list.
l1=list(filter(iseven, l)) print(l1)
Map() Function Theory
For every sequence, apply some function and generate new values. For example, let’s say we have l = [1,2,3,4,5]. And we want the square of all the values.
So it will have new values 1, 4, 9, etc.
Def squareit(n): Return n*n l1=list(map(squareit, l)) print(l1)
We can use it for multiple sequences as well.
Here, if there are 10 input values, then the output is 10 or less than 10.
While in the reduce function, whatever the number of elements, the sequence of elements becomes one.
l=[10, 20 , 30 , 40 , 50] reduce(lambda x,y:x+y, l) print(reduce)
It will add all elements of the list and give one output.
*Reduce function is not a Python inbuilt function so it needs to be imported explicitly from the functools module:
from functools import reduce
In this article, I covered the basic concepts of functions in Python. Now you guys must have a sense of what Functions exactly are and the different components of Python functions.
You can now try writing more functions as it is one of the best practices in any programming language!