Welcome to the world of Functions. This is undoubtedly the most important topic of your Data Science career 😛
Function will make your life easy and your peer’s life easier !!
Toh shuru karte hain, bina kisi bakchodi ke
(Let’s start without wasting any time)
Defining a function
A function is a block of code which runs only when it is called. Let’s start with defining a basic function:
You can also define
Information is passed in a function as a parameter. In the above example, x and y are two parameters.
Arguments are the values passed to these parameters. 4 and 5 are the arguments of the function sum()
Using a default parameter – You might need a default parameter in case no value is passed to the function. It is done in the following way
Write a function to get the Maximum out of two number
You can also create a function without any name, it is called
Let’s learn the basics of
Below is the lambda function to add two numbers.
A lambda function to get the cube root of a number
Why do we need a Lambda function?
Lambda function is a very convenient way to write small functions, but the real power of a Lambda function relies on the point that you can use it within a function. Let’s see how a lambda function can be used in a better way:-
Look at the above function hello. It has a parameter n which is passed as the string “Data”. This string is saved in x. Now if you pass a number to “x”, then it will be used as a and will multiply Data with 4 in this case.
When you don’t know the number of arguments to pass to a function, then you need to pass a variable parameter.
What *args allows you to do is take in more arguments than the number of formal arguments that you previously defined. With *args, any number of extra arguments can be tacked on to your current formal parameters (including zero extra arguments).
Below is how a variable parameter is passed to a pizza function.
You can use
**kwargs to let your functions take an arbitrary number of keyword arguments (“
The special syntax **
Few questions which you should try from the previous exercises are:-
1. What is the difference between tuple and list?
2. How to store a dictionary in a list?
3. How to store a list in a dictionary?
4. Create a list using a loop and fill the list with
5. Write a program to sum all the elements of the list.
You can either go through the previous
For more questions and answers like this, you can purchase our ebook from Amazon. Link below
100 Python Questions to crack Data Science/Analyst Interview
Keep practicing 🙂