Python Quiz 3 | Daily Quiz 3

Python Quiz for Data Science

Try the following quiz, it has 10 fairly simple questions on minute Python concepts.
Comment your score below and do mention if you would like to have more quizzes.
Python for Data Science

We will obviously increase the level of questions and will be covering SQL, R, Machine Learning, Statistics and Python Questions
Python quiz

[quiz-cat id=”4722″]

Python Quiz

Youtube Channel – The Data Monk

We have recently started with our Youtube Channel and have currently 50+ videos on covering SQL, Pandas, Numpy, Statistics and Interview Questions
Channel – The Data Monk
You can subscribe if you want to prepare for Analytics interviews

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

Python MCQ | Daily Quiz Day 2

Python Quiz for Interview

Try the following quiz, it has 5 fairly simple questions on minute Python concepts.
Comment your score below and do mention if you would like to have more quizzes.
Python for Data Science

We will obviously increase the level of questions and will be covering SQL, R, Machine Learning, Statistics and Python Questions

Python Quiz for interview

[quiz-cat id=”4683″]

Python Quiz for Interview

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

Python for Data Science | Quiz 1

Python for Data Science

Try the following quiz, it has 5 fairly simple questions on minute Python concepts.
Comment your score below and do mention if you would like to have more quizzes.
Python for Data Science

We will obviously increase the level of questions and will be covering SQL, R, Machine Learning, Statistics and Python Questions

[quiz-cat id=”4654″]

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

Visualization in Python Part 2

We have already plotted some basic graphs. Now it’s time to plot some more graphs:-

Line Histogram

Now let’s create a line histogram with some random data

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
noise = np.random.normal(0, 1, (1000, ))
density = stats.gaussian_kde(noise)
n, x, _ = plt.hist(noise, bins=np.linspace(-3, 3, 50),histtype=u’step’, density=True) 
plt.plot(x, density(x))
plt.show()

Graph 13 – A line histogram

Variable Width histogram

This is how a variable column width histogram looks like

Let’s create one with our dataset

import numpy as np
import matplotlib.pyplot as plt
freqs = np.array([2, 7, 21, 15, 12])
bins = np.array([65, 75, 80, 90, 105, 110])
widths = bins[1:] – bins[:-1]
heights = freqs.astype(np.float)/widths
plt.fill_between(bins.repeat(2)[1:-1], heights.repeat(2), facecolor=’orange’)
plt.show()

Graph 14 – A variable width histogram

One more example belowimport numpy as np
import matplotlib.pyplot as plt
x = np.sort(np.random.rand(6))
y = np.random.rand(5)
plt.bar(x[:-1], y, width=x[1:] – x[:-1])
plt.show()

Graph 15 – Variable width histogram

Area Chart

Below is how an area chart looks like:

Let’s create a basic area chart with some dummy data

Import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Data
x=range(1,6)
y=[ [1,4,6,8,9], [2,2,7,10,12], [2,8,5,10,6] ]

# Plot
plt.stackplot(x,y, labels=[‘A’,’B’,’C’])
plt.legend(loc=’upper left’)
plt.show()

Graph 16 – A basic area chart

You already know how to add x-labels, y-labels, title, etc.
Go ahead and add these in the graph above

Box and Whisker Plot

A box and whisker plot, or boxplot for short, is generally used to summarize the distribution of a data sample.
The x-axis is used to represent the data sample, where multiple boxplots can be drawn side by side on the x-axis if desired.

Box plot is one of the most common type of graphics. It gives a nice type of summary of one or more numeric variables. The line that divides the box in the two half is the median of the numbers.
The end of the boxes represents

seed(123)
a = random.sample(range(1,100),20)
b = random.sample(range(1,100),20)
c = random.sample(range(1,100),20)
d = random.sample(range(1,100),20)
list_Ex = [a,b,c,d]
plt.boxplot(list_Ex)

Graph 17 – A basic Box-Whisker graph

Now we will try to make the graph look better by adding color to the plot. The box-plot shows median, 25th and 75th percentile, and outliers. You should try to give different color to these points to make the plot more appealing.

When you plot a boxplot, you can use the following 5 attributes of the plot:-
a. box – To modify the color, line width, etc. of the central box
b. whisker – To modify the color and line width of the line which connects the box to the cap i.e. the horizontal end of the box plot
c. cap – The horizontal end of the box
d. median – The center of the box
e. flier

The box denotes the 1st and 3rd Quartile and it is called IQR i.e. the Inter Quartile Range. The lower fence is at Q1 – 1.5*IQR and the upper fence is at Q3 + 1.5*IQR. Any point which falls above or below it is called fliers or outliers

Following is the code with some fancy colors to help you understand each term individually.

bp=plt.boxplot(list_Ex,patch_artist = True)
for box in bp[‘boxes’]:
    box.set(color=’orange’,linewidth=2
for whisker in bp[‘whiskers’]:
    whisker.set(color = ‘red’,linewidth=2)
for cap in bp[‘caps’]:
    cap.set(color=’green’,linewidth=2)
for median in bp[‘medians’]:
    median.set(color=’blue’,linewidth=2)
for flier in bp[‘fliers’]:
    flier.set(marker=’o’,color = ‘black’, alpha=0.5)

Graph 18 – Box Whisker Chart

Box-plot practice

Following is one more code with the help of which you can replicate a Gaussian distribution

from numpy.random import seed
from numpy.random import randn
from matplotlib import pyplot

seed(1)
# random numbers drawn from a Gaussian distribution
x = [randn(1000), 5 * randn(1000), 10 * randn(1000)]
# create box and whisker plot
pyplot.boxplot(x)
# show line plot
pyplot.show()

Graph 19 – A Box-Whisker Plot

Scatter plot

Scatter plot is an easy to make but interesting visualization which gives a clear picture of how the data is distributed.

Let’s take example of 10 innings played by Sachin, Dhoni, and Kohli and see how their scores are distributed. The code is fairly easy to understand

sachin = [89, 90, 70, 89, 100, 80, 90, 100, 80, 34]
kohli = [30, 29, 49, 48, 100, 48, 38, 45, 20, 30]
dhoni = [23,45,67,76,65,45,100,12,34,65]
run = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
plt.scatter(run, sachin, color=’red’)
plt.scatter(run, kohli, color=’green’)
plt.scatter(run,dhoni,color=’blue’)
plt.xlabel(‘Score Range’)
plt.ylabel(‘Run scored’)
plt.show()

You can also add legend in the plot by using the following command

legend = [‘sachin’,’kohli’,’dhoni’]
plt.legend(legend)
The plot will now look like this

Graph 20 – A scatter plot

Below is one more scatter plot where you give weighted area and the size of the circle will be on the basis of the circle

import numpy as np
np.random.seed(123)
x = random.sample(range(1,100),40)
y = random.sample(range(1,100),40)
colors = np.random.rand(N)
area = (30*np.random.rand(N))**2
plt.scatter(x,y,s=area,c=colors,alpha=0.5)
plt.show()


Graph 21 – A scatter plot with area of bubble denoting the volume

Pie Chart

Create a pie chart for the number of centuries scored by Sachin, Dhoni, Dravid, and Kohli.

labels = ‘Sachin’,’Dhoni’,’Kohli’,’Dravid’
size = [100,25,70,50]
colors = [‘pink’,’blue’,’red’,’orange’]
explode = (0.1,0,0,0)
plt.pie(size,explode=explode,labels=labels,colors=colors,autopct=’%1.1f%%’,shadow=True,startangle=140)
plt.axis(‘equal’)
plt.show()
explode is used to set apart the first part of the pie chart. Everything else in the code is self explanatory. Below is the plot

Graph 22 – Pie chart showing performance of cricketers

Some cool  Visualizations

Create a stacked chart to demonstrate the number of people voting for either Python or Java in 5 countries, namely, India, USA, England, S.A., Nepal

import numpy as np
import matplotlib.pyplot as plt
Python = (20, 35, 30, 35, 27)
Java = (25, 32, 34, 20, 25)
width = 0.35       # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, Python, width)
p2 = plt.bar(ind, Java, width,bottom=Python)
plt.ylabel(‘Votes’)
plt.title(‘Number of people using Python or Java’)
plt.xticks(ind, (‘India’, ‘USA’, ‘England’, ‘S.A.’, ‘Nepal’))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), (‘Python’, ‘Java’))
plt.show()


xticks is used to give labels to the x-axis and yticks give labels to the y-axis.

Graph 23 – Stacked Bar graph

A cool area graph

import numpy as np
import matplotlib.pyplot as plt
# create data
x=range(1,15)
y=[1,4,6,8,4,5,3,2,4,1,5,6,8,7]

# Change the color and its transparency
plt.fill_between( x, y, color=”red”, alpha=0.4)
plt.show()
# Same, but add a stronger line on top (edge)
plt.fill_between( x, y, color=”red”, alpha=0.2)
plt.plot(x, y, color=”red”, alpha=0.6)

The parameter alpha is used to give weight age to the density of color. 0.4 is given to the edge and 0.2 is given to the fill

Graph 24 – An area graph

One of the most important thing is to understand when to use which graph and a list of all the graphs in your knowledge.

There are four types of information which we can display using any plot:-
1. Distribution
2. Comparison
3. Relationship
4. Composition


1. Distribution shows how diversely the data is distributed in your data set.
How many people are from which state of the country?

a   Histogram – If you have few data point
b.  Line Histogram – When you have a lot of data points
c.   Scatter plot – When you have to show the distribution of 2-3 variables

2.    Comparison – When you have to compare something over 2 or more categories

a. Variable width chart – When you have to compare two variables per item
b. Tables with embedded charts – When there are many categories, basically a matrix of charts
c. Horizontal or Vertical Histogram – When there are few categories in a data set
d. If you want to compare something over time
    i.    Line Chart
   ii.   Bar Vertical Chart
   iii.  Many categories line chart

3. Relationship Charts – When you want to see the relationship between two or more variables then you have to use relationship charts

a. Scatter Plot
b. Scatter plot bubble chart

4. Composition Charts –
When you have to show a percentage or composition of variables.

a. Pie Chart – Very basic plot when there are 3-6 categories
b. Stacked 100% bar chart with sub component – When you have to show components of components
c. Stacked 100% bar chart – When you have to look into the contribution of each component.
d. Stacked area chart – When relative and absolute difference matters



Visualizations in Python

Data visualization is the discipline of trying to understand data by placing it in a visual context so that patterns, trends and correlations that might not otherwise be detected can be exposed. It  is one of the basic but a very important weapon in your Data Science career.
Python is blessed with some good libraries for visualizations. 

Open Jupyter notebook or any other IDE of your preference.

Library to use – There are a lots of good visualization libraries, but matplot library is the most preferred one to start with because of its simple implementation.
So,We will mostly concentrate on matplot library.

Importing the library and giving it the standard alias as plt.

Following are the two important functions which will come handy in this book:-

To display a chart you should use – plt.show()
To save the chart as an image, use the code – plt.savefig(β€œFilename.png”)

Popular plotting libraries in Python are:-

1. Matplotlib – Best to start with. It provides easy implementation and gives a lot of freedom
2. Seaborn – It has a high level interface and great default styles
3. Plotly – To create interactive plots
4. Pandas Visualization – Easy interface, built on Matplotlib

Line Chart

A line chart or line graph is a type of chart which displays information as a series of data points called β€˜markers’ connected by straight line segments.

So, a line plot is a very basic plot which is used to show observations collected after a regular interval. The x-axis represents the interval and the y-axis represents the values.

Lets plot our first graph
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6]
y = [10,12,20,21,30,35]
plt.plot(x,y)
Here is what you will get

Graph 1 – Basic Line Chart

Plot a sin graph using line plot

import matplotlib.pyplot as plt
from numpy import cos

x = [x*0.01 for x in range(100)]
y = cos(x)
plt.plot(x,y)
plt.show()


Here is what you get as a cos graph

Graph 2 – Cos graph using line plot

You know how to plot a line graph, but there is one important thing missing in the graph i.e. the x and y-axis, and the plot title. Let’s create another line plot for number of students in a class for the following data

c = [1,2,3,4,5,6]
student = [40,52,50,61,70,78]

Following commands are used to put x-axis label, y-axis label, and chart title

plt.xlabel(β€œLabel”)
plt.ylabel(β€œLabel”)
plt.title(β€œTitle”)

The code is given below
c = [1,2,3,4,5,6]
student = [40,52,50,61,70,78]
plt.xlabel(“Class”)
plt.ylabel(“Number of Students”)
plt.title(“Class vs Number of students”)
plt.plot(c, student)

Graph 3 – Class vs Number of Students chart with proper labels and plot title

Do you want to change the color of the line?
Try the following code instead to make the line green in color
plt.plot(c,student,color=’g’)

Graph 4 – Adding color to the same graph

Multi Line Chart

You can also add multiple plots in the same graph. Let’s try to put a couple of new lines in the graph i.e. number of teachers and average marks

Graph 5 – Adding multiple lines to a graph

To add a legend, you have to give label to each of the line which you want to plot and after that you specify a location to the legend

The code is self explanatory and is given below:-

c = [1,2,3,4,5,6]
student = [40,52,50,61,70,78]
avg_marks = [34,43,54,44,50,55]
num_of_teachers = [10,12,13,10,15,10]
plt.xlabel(“Class”)
#plt.ylabel(“Number of Students”)
plt.title(“Class vs Number of students”)
plt.plot(c,student,color=’orange’,label=’Student’)
plt.plot(c,avg_marks,color=’red’,label=’Marks’)
plt.plot(c,num_of_teachers,color=’green’,label=’Teachers’)
plt.legend(loc=”upper left”)


Bar Chart

β€œA bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally.”

After the line chart, the second basic but highly used chart is the bar chart

To create a bar chart – plt.bar(x,y)

We will plot few graphs first and then you can put labels, title, and legends later.

import matplotlib.pyplot as plt
a = [‘Apple’,’Mango’,’Pineapple’]
b = [40,60,50]
plt.bar(a,b)

Graph 6 – A simple bar chart

Use random values between 1 and 100 to create the same graph.

import matplotlib.pyplot as plt
from random import seed
from random import randint
seed(123)
x = [‘Apple’,’Mango’,’Pineapple’]
y = [randint(0,100),randint(0,100),randint(0,100)]
plt.bar(x,y)

Graph 7 – Bar chart with random values

Adding color, labels, and title to the random values bar chart

Stacked 100% bar chart with sub component
When you have to show components of components like the graph below

Example of 100% bar chart

x = [“a”,”b”,”c”,”d”]
y1 = np.array([3,8,6,4])
y2 = np.array([10,2,4,3])
y3 = np.array([5,6,2,5])

snum = y1+y2+y3

# normalization
y1 = y1/snum*100.
y2 = y2/snum*100.
y3 = y3/snum*100.
plt.figure(figsize=(4,3))

# stack bars

plt.bar(x, y1, label=’y1′)
plt.bar(x, y2 ,bottom=y1,label=’y2′)
plt.bar(x, y3 ,bottom=y1+y2,label=’y3′)

Graph 8 – A 100% stacked bar chart

Histogram

Histograms are density estimates. A density estimate gives a good impression of the distribution of the data. The idea is to locally represent the data density by counting the number of observations in a sequence of consecutive intervals (bins).

To plot a histogram use this code – plt.hist(x,y)

A simple histogram plot
q = [1,2,34,5,44,66,66,90,33,45,2,1,2,3,4]
plt.hist(q,bins = 3,color=’green’)

Graph 9 – A simple histogram

Create a list using random variables and plot it in 4 bins

import random
my_rand = random.sample(range(1,30),20)
print(my_rand)
print(type(my_rand))
plt.hist(my_rand,bins=4,color=’orange’)

Graph 10 – A histogram made with random variables

In Histogram also you can add more than one data points to make parallel bars.

import random
my_rand = random.sample(range(1,30),20)
my_rand2 = random.sample(range(1,25),20)
print(my_rand)
print(type(my_rand))
plt.hist([my_rand,my_rand2],bins=4,color=[‘green’,’red’])
legend = [‘Rand1′,’Rand2’]
plt.legend(legend)
plt.xlabel(“Bins”)
plt.ylabel(“Random Number”)
plt.title(“Random Variable distribution”)

Graph 11 – Parallel histogram

Horizontal Histogram

import numpy as np
import matplotlib.pyplot as plt
name = [‘Nitin’,’Saurabh’,’Rahul’,’Gaurav’,’Amit’]
run = [200,70,130,120,100]
plt.barh(name,run,color=’orange’)
plt.xlabel(“Runs Scored”)
plt.ylabel(“Cricketer”)
plt.title(“Runs scored by cricketers”)
plt.show()

Graph 12 – A horizontal histogram

Keep making irrelevant and unnecessary graphs.
Keep practicing πŸ™‚

XtraMous

Reading and Writing files in Python

You always have to read and write files when working for a company or Hackathon. So, it’s necessary to know how to read different types of files.

Let’s start the boring but important part

The most important command to open a file in Python is the open() method. It takes two parameters, Name of the file and action mode.

Like most of the other programming languages, Python has 4 modes to access a file:-
1. “r” – Read – Reads a file
2. “a” – Append – Appends a file or create a new file
3. “w” – Write – Writes a new file
4. “x” – Create – Creates the specified file

Apart from these you can also specify the format in which you want to open the file:
1. t for Text(Default)
2. b for Binary file

Open a file
x = open(“Analytics.txt”,”rt”)
It opens the file, basically reads it in text format

Read the file

You can also read the file line by line by the following method or by using readline() method

Write something in a file

Delete a file

Use the “os” package and then run the remove() command
import os
os.remove(“file name”)

God forbid, if you ever have to delete a folder and want to look cool in front of your friends, you can use the following command

os.rmdir(“Name of directory”)

Reading CSV file
Comma Separated Values or CSV file format is one of the most used file formats and you will definitely come across reading a csv file often.
In order to read it, you should ideally import pandas library

import pandas as pd
x = pd.read_csv(“File Path”)

P.S. – This will convert the file in a Data Frame

You can read about different parameters here

There are a lot of file formats, but we covered only those which are of utmost important. In case you need more information, try this link from Data Camp or you can trust your best friend StackOverFlow πŸ˜›

If you need information about a specific file format, do comment below.

Keep learning πŸ™‚

XtraMous

Tricky Interview Questions (Python)

The reason why I put interview questions as the title of a lot of posts is because:
1. It makes you click on the post
2. It makes you feel that these are very important questions and you can nail an interview with it
3. These are actual interview questions asked in companies like Myntra, Flipkart, BookMyShow, WNS, Sapient, etc.
4. You have to practice to become perfect. You can practice here or anywhere else. But make sure you know all the questions given below.


Toh suru karte hain bina kisi bakchodi ke
Let’s start with the questions πŸ˜›

1. Which data type is mutable and ordered in Python?
List

2. Can a dictionary contain another dictionary?
Yes, a dictionary can contain another dictionary. In fact, this is the main advantage of using dictionary data type.

3. When to use list, set or dictionaries in Python?
A list keeps order, dict and set don’t: When you care about order, therefore, you must use list (if your choice of containers is limited to these three, of course;-).

dict associates with each key a value, while list and set just contain values: very different use cases, obviously.
set requires items to be hashable, list doesn’t: if you have non-hashable items, therefore, you cannot use set and must instead use list.

4. WAP where you first create an empty list and then add the elements.
basic_list = []
basic_list.append(β€˜Alpha’)
basic_list.append(β€˜Beta’)
basic_list.append(β€˜Gamma’)

5. What does this mean: *args, **kwargs? And why would we use it?
We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargsis used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.

6. What are negative indexes and why are they used?
The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses β€˜0’ that is uses as first index and β€˜1’ as the second index and the process goes on like that.

7. Randomly shuffle the content of a list

8. Take a random sample of 20 elements and put it in a list

9. Take a list and sort it

10. Explain split() and sub() function from the “re” package
split() – uses a regex pattern to β€œsplit” a given string into a list
sub() – finds all substrings where the regex pattern matches and then replace them with a different string

11. What are the supported data types in Python?
The most important data types include the following:
1. Number
2. String
3. List
4.Tuple
5. Dictionary
6. Set

12. What is the function to reverse a list?
list.reverse()

13. How to remove the last object from the list?
list.pop(obj=list[-1])
Removes and returns last object or obj from list.

14. What is a dictionary?
A dictionary is one of the built-in data types in Python. It defines an unordered mapping of unique keys to values. Dictionaries are indexed by keys, and the values can be any valid Python data type (even a user-defined class). Notably, dictionaries are mutable, which means they can be modified. A dictionary is created with curly braces and indexed using the square bracket notation.

15. Python is an object oriented language. What are the features of an object oriented programming language?
OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are:
Encapsulation, Data Abstraction, Inheritance, Polymorphism.

16. What is the difference between append() and extend() method?
Both append() and extend() methods are the methods of list. These methods a re used to add the elements at the end of the list.
append(element) – adds the given element at the end of the list which has called this method.
extend(another-list) – adds the elements of another-list at the end of the list which is called the extend method.

17. Write a program to check if a string is a palindrome?
Palindrome is a string which is symmetric like. aba, nitin, nureses run, etc

Below is the code, write it down yourself πŸ˜›

18. Take a random list and plot a histogram with 3 bins.

19. What is the different between range () and xrange () functions in Python?
range () returns a list whereas xrange () returns an object that acts like an iterator for generating numbers on demand.

20. Guess the output of the following code
x = “Fox ate the pizza”
print(x[:7])

You can find Python interview questions on many websites, we will keep on updating this list. Time for some marketing, if you want to get some more interview questions on Python, then click below:-

100 Python Questions to crack Data Science/Analyst Interview

Keep practicing πŸ™‚

XtraMous


Functions in Python

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:

Hello World program using a function

You can also define simple function to add two numbers and by passing values to the function

Simple function to sum two numbers

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

Using both an argument and default parameter

Write a function to get the Maximum out of two number

You can also create a function without any name, it is called Lambda function. It is a small anonymous function which can take any number of arguments, but can have only one expression.

Let’s learn the basics of Lambda function.
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.

Passing variable number of arguments in a pizza function

**kwargs
You can use **kwargs to let your functions take an arbitrary number of keyword arguments (“kwargs” means “keyword arguments”)

The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.

A simple example of kwargs


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 square of numbers from 1 to 10.
5. Write a program to sum all the elements of the list.

You can either go through the previous days session or google these out.
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 πŸ™‚

XtraMous


Loop in Python

Loop and functions are two most important topics in the basics of Python. You need to have a really good hand on loop and functions.

Loop is basically used to iterate the same thing again and again. Python, like most of the programming language, have two types of loop:-
1. while
2. for

While loop
In a while loop, a condition is checked first and then the content or body of the loop is executed.
A simple while loop is executed below

There are two more keywords which are used inside the body of a loop:-
1. break
2. continue

Break command is used to stop a loop at a particular condition and it pulls the control out of the loop. See the example below

Break statement stops the loop at the given condition

Continue statement is used to bypass a particular instance

Use of continue statement

2. For loop

A for loop is used for iterating over a sequence which could be anything like a list, a tuple, a dictionary or a set.

Let’s understand each with the help of some examples:

a. Applying loop on a list

b. Applying loop on a list with break statement

c. Using range keyword. Range starts with 0 and ends at n-1 where n is the parameter in the range() function

d. Using range keyword with increment

e. Nested loop

f. Looping through all the key-value pair of a dictionary

g. Looping through all the values of a dictionary

h. Looping through all the keys of a dictionary

i. Print the following pattern
1
22
333
4444

j. Reverse a list using loop

h. Reverse a string using loop, example to do it without loop is given below:

If you want to learn more about some tricky Python Questions then do check out our book on Amazon

1. 100 Python Questions to crack Data Science/Analyst Interview
2. The Monk who knew Linear Regression (Python): Understand, Learn and Crack Data Science Interview

Keep practicing Machaa πŸ™‚

XtraMous

Python – Conditional Statements

One of the most important thing which you need to learn in Python is the use of conditional statement.
These are small code snippets which will help you solve multiple problems in a project or any hackathon.

Conditional statements help us to apply a particular constraint on the data set. Suppose you want to pull the data only for a particular employee or user; or you want to filter the data for a particular date; or you want to count how many male and female are there in the given data set, every where you will be using these conditional statements.

Every programming language have almost the same conditional statement and Python is not an anomaly.

We will try to keep it crisp in this post but it will keep on haunting you in the upcoming posts, so, try to learn the basics here before proceeding.

There are three types of conditional statement used in Python:
1. if
2. else
3. elif

Python, like other programming languages, supports the usual logical conditions:

1. Equals: x == y
2. Not Equals : x != y
3. Greater than : x>y
4. Greater than or equal to : x >= y
5. Less than : x < y
6. Less than or equal to : x <= y

1. if is simple conditional operator where you put a condition and filter the data set or mould the data set in a particular manner.

P.S. – Python follows indentation religiously, so be very careful in writing codes

A simple example of if operator

2. else operator compliments the if operator. Suppose, the if condition is not satisfied, then the control will move to else

A simple if and else combo

3. elif helps in putting as many conditions in your program as you like. Look at the example below

A simple example of all the three conditional statements

Let’s try some more examples
1. Applying more than one condition using “and” keyword

2. Applying more than one condition using “or” operator

3. Applying condition on a list

4. Apply condition on a string

5. Multiple if statement

6. If the first “if” condition is true, then the conditional statements will break and even if the “else” condition is true, the control will not go to it. See the example below where both, if and else statements are true

7. if True condition

Summary of the day
1. You learned the basics of if, else and elif conditional statements
2. You can run multiple conditional statements in a nested query
3. You have practiced a few examples of using the conditional statement in different ways

If you have time, make a small calculator using everything you have learnt today

A very simple calculator using if statement

Keep practicing πŸ™‚