Introduction to Python Functions for Data Science Beginners

Aashish Last Updated : 27 Oct, 2024
6 min read

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

Introduction

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.

Python Style Guide Featured Image

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

With an introduction to Python, we can understand that when we learn machine learning and data science, we come to know that the algorithms we use are essentially functions. In this article, we’ll cover the basics of Python functions and how to use them.

 

Table of Contents

  1. Types of Python Functions
  2. Functions Parameters
  3. Return Statement
  4. Arguments
  5. Types of Variables
  6. Recursive Functions
  7. Lambda Functions
  8. Filter() Function
  9. Map() Function
  10. 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:

wish()

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:

def wish(name):
  print("Hello" , name, "Good Evening")
wish("ABC")

 

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:

print(add(10, 20))

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.

Positional Arguments

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.

Keywords Arguments

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.

 

Default Arguments

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:

f1(*n)

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

  • f1()
  • f2()

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.

 

Recursive Functions

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.

 

Lambda Functions

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:

filter(function, sequence)

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.

 

Reduce() Function

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

 

End Notes

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!

Responses From Readers

Clear

Ayush
Ayush

This is seriously one of the best and a very simplistic language blog i have came across, i think the whole topic is been covered which i was not getting exactly in any video, every video was having something but not this much coverage of topic and that too in a simpler manner, Kudos to the author and AV.

Vikas kaushik
Vikas kaushik

Very well written. Good work

Abhishek
Abhishek

It's really very knowledgeable...nicely written

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details