Functions in Python | Python for Data Science | Day 9

The Data Monk is back with a fresh topic for you. It’s time to discuss functions in Python. 
In plain vanilla terms, functions in Python are reusable pieces of code. Basically, functions allow you to name a block of code i.e. a group of statements that can be reused using that name anywhere in the program. 

Functions in Python

You know the drill! We will be discussing functions by taking code instances. So, let’s get started.

Firstly, let’s discuss the syntax of functions.

def function_name(param1, param2,…….):

# job to be done

return

A function starts with one keyword called “def”, followed by the name of the function. This is the name you will use whenever you use it in the program in future. So, make sure the name is intuitive and descriptive of what it does. For instance, if the function is used to find the product of two numbers, it is better to name it multiply or product rather than naming it abc or xyz. Within the braces, we specify the parameter list. These are the quantities that will be used in the function program. Then, we mention a code block which mentions what the function does, when it will be called. Finally, we use the return statement to save the result in a variable. The return statement is not mandatory. 

Let’s look at the code samples below to understand functions completely.

Consider the “add1” function below. It just prints the sum of the arguments passed. When we print the value of sum1, it turns up “None” because the function does not use a return statement. Thus, “3” only gets printed due to the print statement and is not saved to the variable “sum1”.

Functions in Python

Now, let’s use the same function but his time, with “return”. Carefully see that now sum2 is displayed as 3 and not none. This is because of the “return” statement used in the function.

Functions in Python

It is important to understand that a and b are the parameters of the function whereas 1 and 2 are the arguments.

ParametersArguments
Parameters are used in the function definitionArguments are the actual values passed to the function in its call.

Now, let’s consider another example.

Here, d=10 is the default argument. Default argument means that the function will assume it’s value to be 10 unless stated otherwise. So, observe in the image below that when the function is called for the first time, 10 was not mentioned in the argument list but it is printed as 10. Whereas, in the second function call, when d is passed as 40, it is printed as 40.           

If in the parameter list, you mention the parameters in an order. When you pass the arguments in the function call, it evokes the same order. But if you do not intend to use the same order, you will have to name the arguments in the call. If it appears overwhelming at the moment, refer to the code below and it will become crystal clear.

In the first call, a is attributed to “data”, b is attributed to “the” and c is attributed to “monk”. So, in the second call, we explicitly specify these arguments so that we get them printed in the desired fashion.

Carefully look at the code below. 

The default arguments (d, e) are always specified after the required arguments (a, b, c). In the function call, we wish the function to take the default value for d and use the passed argument for e. That is the reason we mentioned e= “frenzy” in the call. These little things do make a significant difference. Otherwise, d would have been attributed to frenzy. And the output would have been :

In Python, we can also pack the arguments. Look at the code snippet below:

If you do not know how many arguments you will pass to the function, you can simply use *args to pack all of them together, like we did in the function above.

What if you wish to create a function that has a minimum no. of fixed or required arguments, and some other arguments which you are not sure about. How will such a function appear? See below:

Alright, so we have created the function that has 3 required arguments (x, y, z) and the rest of them are packed as *args. 

Can you guess what output will be produced if I type in this line of code:

func3(“lets”, “learn”)

Open your notebooks and try!

Did you get the same error?

We tried some other ways to explore the function behaviour. You can try them too.

Moving on, let’s increase the complexity level a bit, and try a function that consists of required arguments, packed arguments and default arguments.

An exercise for you:  Try calling this function in two ways:

  • Without passing d and e
  • By passing d and e

Here are the two calls:

Alright, now let’s try another type of arguments called key-worded arguments, used in the code as **kwargs.

Key-worded arguments are packed in a dictionary. Consider the instance below:

Note that the keworded arguments i.e, data and monk are printed in a dictionary.

So, with this, we end our tutorial on functions. You can read more about them here: https://www.tutorialspoint.com/python/python_functions.htm 

To hone your knowledge, we have curated a set of questions for your practice. Make sure you attempt them on your own, before seeking help from the provided solutions. 

Until next time, folks!

The Data Monk Interview Books – Don’t Miss

Now we are also available on our website where you can directly download the PDF of the topic you are interested in. At Amazon, each book costs ~299, on our website we have put it at a 60-80% discount. There are ~4000 solved interview questions prepared for you.

10 e-book bundle with 1400 interview questions spread across SQL, Python, Statistics, Case Studies, and Machine Learning Algorithms – Ideal for 0-3 years experienced candidates

23 E-book with ~2000 interview questions spread across AWS, SQL, Python, 10+ ML algorithms, MS Excel, and Case Studies – Complete Package for someone between 0 to 8 years of experience (The above 10 e-book bundle has a completely different set of e-books)

12 E-books for 12 Machine Learning algorithms with 1000+ interview questions – For those candidates who want to include any Machine Learning Algorithm in their resume and to learn/revise the important concepts. These 12 e-books are a part of the 23 e-book package

Individual 50+ e-books on separate topics

Important Resources to crack interviews (Mostly Free)

There are a few things which might be very useful for your preparation

The Data Monk Youtube channel – Here you will get only those videos that are asked in interviews for Data Analysts, Data Scientists, Machine Learning Engineers, Business Intelligence Engineers, Analytics Manager, etc.
Go through the watchlist which makes you uncomfortable:-

All the list of 200 videos
Complete Python Playlist for Data Science
Company-wise Data Science Interview Questions – Must Watch
All important Machine Learning Algorithm with code in Python
Complete Python Numpy Playlist
Complete Python Pandas Playlist
SQL Complete Playlist
Case Study and Guesstimates Complete Playlist
Complete Playlist of Statistics

Author: TheDataMonk

I am the Co-Founder of The Data Monk. I have a total of 6+ years of analytics experience 3+ years at Mu Sigma 2 years at OYO 1 year and counting at The Data Monk I am an active trader and a logically sarcastic idiot :)