Python Interview Questions | Python Tutorial | Intellipaat

Python Interview Questions | Python Tutorial | Intellipaat


Hey guys, welcome to the session by Intellipaat. So their is a huge demand for Python and Python programmers out there.
Being more style in nature, Python can be used for web development, machine
learning, deep learning and multiple other tasks. So now you guys must be
wondering, what sort of questions are asked by the top companies when it comes
to Python the interview? So in today’s session, we’ve come up with this Python
interview questions so that you can ace any Python interview that you attend and
you guys also have to make sure that you implement all of the coding part by
yourselves so that you gain the required expertise. Now let’s actually start off
by having a glance at the job trends of different programming languages. So here
we are comparing Python, R, Angular and C and it’s very obvious that Python is
the most preferred language across various industries. So you see this blue
color line over here. So this blue colored line is for the Python
programming language and if you closely observe this blue colored line, you will
observe that the popularity of Python has been steadily increasing over the
years. So now that we know how popular Python is, let’s head on to our interview
questions. Right, so this is our first question. What are keywords in Python? So
you can consider these keywords to be special reserved words which exist for a
specific purpose. Now you cannot use a keyword name as a variable name or an
identifier. So these are some of the keywords which exist in Python such as
true, false, not, continue and so on and in total there are 33 keywords in Python
3.7. Now you also need to keep in mind that these keywords are case sensitive
that is if you look at the keyword True over here then you see that T needs to
be capital. So our next question is what are literals in Python and then we’d
have to explain about the different types of literals. So literals are the
constants used in Python or in other words this is the data which is stored
in a variable and there are four types of literals in Python. So we have string
literals, numeric literals, boolean literals and special literals. So let’s
look at string literals. So you can create string literals by just enclosing
the text within quotes. So here we have created two string literals John and
James. So we see that John has enclosed double quotes and James is enclosed
within single quote. So this is how you can create string literals. Next up we
have numeric literals. So numeric literals comprise of all of the digits.
Now if your numeric literal doesn’t contain any decimal then it is of the
integer type and if your integer is too long than it would be of the long
type and if you are literal consists of a decimal point then it would be a float
and finally we have a complex number which consists of a real part and an
imaginary part. Going ahead, we have boolean literals. So these boolean
literals comprised of just true and false values. They are generally used
when we are dealing with some condition whose output is either true or false. Now
we’ll head on to special literal. So Python consists of the special literal
called as none and it is used to specify a field that is not created. Here in
this example, I have assigned none to the variable val2. So this variable would
basically be empty. So this is our third question. What is a dictionary in Python
and we also have to create a dictionary where the key is fruit name and there
are four fruit names as values. So what dictionary is an unordered collection of
elements and these elements in a dictionary are stored as key value pairs.
For example, here we have our dictionary with the name my dictionary and we have
three key value pairs. So here our first key is 1 and the value for this key is
John. Second key is 2 and the value for this key is Bob and then we have the
final key which is 3 and the value for this is Alice right. Now let’s run the Jupiter notebook and create our own dictionary where the
key is fruit name and the values would be four fruit names. So I’ll name the
dictionary as my dictionary and we can create a dictionary with the help of
these curly braces over here. So I’ll give in the key name which would be
fruit, name and after this I’d have to given
values of four fruit names. So let’s say, my first fruit is apple and then the second
fruit is mango, third fruit would be orange and the fourth fruit would be
guava. Now all I have to do is hit on run and then let me print this out. So I’ll
just type in my dictionary over here right. So we have created a dictionary
with the name my dictionary where the key is fruit name and the values are
apple, mango, orange and guava and if you want to extract the individual key and
individual values this is how we can do it. Now I’ll type in the name of the
dictionary which is my dictionary. I’ll put in dot and then I’ll just type in
keys, I’ll click on run and we see that the key for this dictionary is fruit
name. Similarly if I want all of the values, I just have to type in values
over here, now let me click on run. So for this dictionary, the values are apple,
mango, orange and guava. So our next question. What are classes and objects in
Python? So simply, you can consider a class to be your blueprint and objects
to be real world entities which are defined and created from classes. For
example, over here you can see the actual blueprint of a house. Now this blueprint
can be used for the rapid creation of unlimited number of copies. So these
copies of the blueprint are nothing but your objects and here we have created
three houses or in other words three objects from the original blueprint
which is our class. So I am repeating it. So our class is nothing but a blueprint
and from this blueprint, we’ll be creating a set of objects which are our
real world entities. So over here this house number one, house number two and
house number three are our real world entities which are nothing but objects
created from this class. Next, we’ll have to create a simple class with the name
human which would give out the name and age of the person. So let’s do this right.
So to create a class, I’d have to use the keyword class and then I will give in
the name of the class which would be human. Now inside this, I will create two
variables so the first variable would be name and
initially I’ll just assign none to it. And my second variable would be age
again I’ll assign none to it. So we have created our variables. Now we’d have to
get the value of name and the value of age from the user. So for this, I’d have
to create some definitions or methods and to create a definition I’ll use def
after this I will given the name of the method which would be get name and
inside this I will pass in self, right. So now over here, I’ll just use
the print function and title and enter your name and after this I will get the
name and the self dot name. So basically, self dot name basically means that
whatever value the user enters it would be stored in this name variable of the
object right and I’ll just type in input over here. So this input function is used
so that we can get a value from the keyboard right. So this is how we can get
the name of the person. now similarly, let’s go ahead and get the age of the
person so I will type in Def and I’ll name this method to be get age. Again
I’ll pass in self inside this right. This time, I’ll use print and I’d have to
enter the age. So enter your age and then I’ll store the self.age
equals input again right. So we are created two get methods where we’ll be
getting the name and the age of the user. Now after this, we’d have to print out
the name and the age. So it’ll be def and I’ll create the method to be put name
again this will be self and I’ll just print out the user’s name. So your name
is self.name and then similarly I’ll
create another method which would be put.age and I’ll pass in self inside this.
So for this it would be print of your age is. Let me again put in double
quotes over here right. So your age is it would be self.age. So we have
created our class where we have two variables name and age and have created
four methods and are those from those two methods, I will be getting the name
and age of the person and the rest of the two methods would help me to print
the name and age of the person right. I’ll click on run. So we have created
this class. Now once we create our class which is basically our blueprint, we’ll
have to create the objects from this class. So let’s say, I create an object
and name the object to be person one, now this would be our first instance and I
just have to call in human. So I’m creating a person instance of the human
class. Now from this person object, I will invoke the get name and get age methods.
So person one.get name, let me click on run. I’d have to enter the name of the
person. Let’s say the name of the person is Sam right. So now it’s time to get the
age of the person. So I’ll type in person one.get age, I’ll click on run and
let’s say the age of the person is 28, so now I have successfully feeded in the
name of the person and the age of the person, now it’s time to print out both
of those. So the person one dot put each and person one dot put name so person
one dot would name right so your age is 28 and your name is Sam
right so we have successfully created our class which would print out the name
of the person in the age of the person right so next question what do you
understand by the init method in Python and a flirt we’d have to give an example
of it so you can just consider the init method to be sort of constructed in
Python so it is a special method in a Python class which is used to initialize
the variables so now that we’ve understood what init method is and what
it is used for let’s go ahead and work with this init method so now here what
I’m going to do is create a student class with the init method in it so let
me do that class student and over here I’ll just create the init method and
these are the parameters of this init method self so and after this it’ll
taken the name of the person and after name it will take in the age of the
person and after this it’ll take in the branch of the person all right now
we’ll have to do is just store these values inside the original variables so
that’ll be self dot name equals name and then our next variable is H so self dot
H equals each and then we have the final variable which is branch so it would be
self dot branch equals branch so we have created our in it method now after this
wait so we actually have to put in de F over here because this is actually a
method right so we have created our init method which is basically a constructor
and going add we’ll just create another method which would help us to print all
of these values def trend student and Al deacons self and all right – oh
here spending all of this while he was so print off
NIEM would be self dot name after this we have so let me change this to be aged over
you and this would be self thought each after this we’ll have to print in the
branch so let me just put in branch over here and this would
be self dot branch right so we have created this student class which has the
constructor I’ll click on run now let me create an object of the student class
I’ll name the object to be student 1 and let me go ahead and create an instance
of this now since we have this constructor over here so I can go ahead
and initialize the student object here itself
so I’ll given the name of the student so let’s see the name of the student is Bob
after the age of the student is 12 and then which branch is studying so let’s
say this guy is studying engineering let me just put in engineering over here run
now student 1 dot I will call in the print student method over here
right so we have successfully created this instant student 1 right so what do
you understand by inheritance in Python and then we’ll have to give an example
of it so inheritance refers to the property of one class acquiring the
properties of another class for example let’s see you have inherited your
features or properties from your parents so if you see all this family tree over
here you can understand that treat such as hair color and poor eyesight are
passed from one generation to the next generation so over here this is
generation 1 generation 2 and grandparents so your parents are
inheriting their traits or their features from their grandparents and you
are inheriting your traits from your parents now let’s go ahead to Jupiter
notebook and walk with an example of inheritance so here what we are doing is
we have a base class with the name fruit and this base class is being inherited
by another class citrus now this is our B’s class fruit which has a constructor
and this constructor just prints out I am a fruit now after this what we are
doing is we are creating another class with the name citrus and this class
inherits from the fruit class right so if a class has to inherit another class
in Python we’ll just give the name of the B’s class as a parentheses inside
our new class now again inside the citrus class we have created another
constructor and inside the constructor of the citrus class I am using the super
method so with the help of super method I can invoke the variables and functions
from my super class right so we’re here I want the init method from my
superclass so I’ll just use the super method and I’m invoking the init method
from this fruit class my apart from this init method from the fruit class I would
also print something else so over here I am also printing i’m citrus over here
right and i’ll create an instance of this class citrus and I’ll store it as
lemon so the result is I’m a fruit I’m citrus so this value I’m a fruit is
coming from the superclass and this value I’m citrus is coming
new class or the child class so this is how we can do single level inheritance
in Python so next so what is numpy and how can you create a basic 1d and 2d
numpy array well numpy is the most widely used
Python library for planar algebra and it is used for performing mathematical and
logical operations on arrays and to import the numpy library in Python you
just have to use the command input down pipe so again let’s head to chop it a
notebook and create a 1d numpy array and a 2-d numpy array so I’ll start off by
typing import numpy as NP after this I’ll create my 1d numpy array so e
equals NP dot Parikh now I will given a list of values so this is my 1d array E
and then let me just print it out so this is my 1d array which comprised of
the values 1 2 n 3 now I’ll go ahead and create a 2d array with the name B so
again the syntax would be the same and P dot array so it’ll be ski comprised of a
list of lists so the first list would comprise of 1 2 & 3 and the second last
word comprised of 4 5 & 6 let me print this out
right so this is our 2d array which comprises of 1 2 3 4 5 & 6 so this time
we’d have to initialize a Phi cross Phi numpy array comprising of all the zeros
so there’s a Phi cos Phi umpire that is then it to be Phi ruse by columns and
all of the values need to be 0 and to initialize an array with all zeros we
can just use n P dot zeros method from the number library let me just type in
import numpy as and b and inside e i will just state and B dot zeros and I’d
have to give in the dimensions of this array so the dimensions of this array
are 5 cross 5 let me just print out a so we have
successfully created our phi cross phi numpy array where all of the values are
just zeros now let’s say we have to number is like this so this is our first
number this is a second number first number array comprised of 1 2 & 3
second number array comprised of 4 5 & 6 now I’d have to add the individual
elements so 4 plus 1 needs to become 5 5 plus 2 needs to become 7 and 6 plus 3
needs to become 9 again our first step would be very
simple I’d have to load the number library
import numpy as and be I will go ahead and create my first number array e
equals and B dot array and the values are 1 2 & 3 similarly I
create my second numpy array which is B I’ll change this variable to be equal to
B and the values are 4 5 & 6 now to add the individual elements I’d
have to use the n P dot sum method now inside this I’d have to go in my first
parameter so my first parameter would be the number arrays which I’d have to add
so I want to add a and B and I will set the access to be equal to zero so when I
set the axis value to be equal to 0 this would individually add the elements so
this will do 4 plus 1 5 plus 2 and 6 plus 3 right and this is what we have 4
plus 1 is 5 5 plus 2 is 7 and 6 plus 3 is 9 now let me actually change the axis
value to be 1 and let’s see what do we get
right so now change the axis value to be 1 then the addition happens across the
row so when you do 3 plus 2 plus 1 you get 6 and when you do 6 plus 4 plus 5
you get 15 so now we will have to get the N largest values from a number I
correct so this is our number I over here and this comprise our 4 3 4 5 6 7
elements 12:43 250 4 5 and 68 and I’d have to get
the first two largest values which over here are 168 now let’s go to Jupiter
notebook and let’s see how can we do this right so again we’ll start off by
putting the number array import numpy us and B and I create this array X is equal
to NP dot array and I’ll given all of these values now to get the indices of
values which are arranged in ascending order we can use the NP dot arc sort
function now what I’ll do is I’ll actually insert a cell below and I’ll go
ahead I’ll do control X I’ll do control V so we have successfully created our
number array let me just print in X over here so this is our numpy right now what
I’ll do is I’ll just copy this and P dot art sword of X and I will print it over
here and let’s see what do we get so what we get over here are index values
so 0 1 2 right 0 1 2 this is our lowest value and then we have 5 so element
index number 5 0 1 2 3 4 5 right 2 5 and then we have 0 which is 12 and then we
have 4 3 right so we basically have the indices of the values arranged in
ascending order so – 5 12 43:54 68 and hundred so this is how it
goes now if I want the indices of the first two highest values then I’ll just
put in – 2 : over here and I have 6 + 3 right 0 1 2 3 4 5 6 so 68 is the second
highest value and then we have 3 0 1 2 3 right so 100 is the first highest value
now what I want to do is I all arranged this in descending order so to arrange
this in descending order again I’ll put in braces over here I’ll put double :
and I’ll put in minus 1 over here and I have sorted the indices in descending
order now if I take all of this I’ll cut this and I will piece this inside of X
I’ll click on run and this is how I get the first two highest values from this
numpy array so 168 are the two highest values from this numpy correct so now
we’d have to give some examples for creating a data frame from list and
dictionary so this is a very common and easy question which is a sin moves of
the Python interviews right so first we’d have to go ahead and create a list
and we’d have to convert that less into a data frame
similarly we will have to create our simple dictionary and convert that
dictionary into a data frame so I’ll type in import pandas a speedy
so I’d have to start up by importing the pandas library now I will go ahead and
create a list so I’ll name this list to be equal to l1
so l1 equals 1 comma 2 comma 3 comma 4 comma 5 so we have created our list now
to convert this list into a data frame all I have to do is use PD dot d our
frame function so here we need to keep in mind that D is capital right PD dot
data frame and I will pass in l1 inside this and I will store this n let’s say
theta 1 and I’ll just print out data 1 over here so we have successfully
created a data frame from a list where the list values of 1 2 3 4 and 5 now
similarly we will create a dictionary and create a data frame out of that
dictionary so I will name this dictionary to be TT 1 and the key is
fruit name and the values are apple mango and let’s see orange
for this we’ll have to create our second key value pair so our second key value
pair would be count and the values would be let’s see 12 24 and 36 right so we
have created this dictionary now again to convert this dictionary into a data
frame we’ll have to use PD dot data frame and I will pass in DT 1 inside
this right so we have created this data frame
where our first column is fruit name in the second column is count and fluid
name comprised of apple mango and orange and the count of the fluids is 12 24 and
36 so now we have this iris dataset which comprises of all of these columns
so we have sepal length sepal width petal length petal width and species now
all of this will have to extract some specified rows based on a condition
should have to extract only those records where the sepal length value is
greater than 5 and the sepal width value is greater than 3 so I’ll start off by
loading the pandas library import Fonda’s as speedy and after this to load
a CSV file I’d have to use the PD dot read CSV function and I’ll given the
name of the file so the name of the file would be iris dot CSV and I’ll just
store this in a new object and name that object to be equal to Iris now let me
have a glance at the head of the stair set iris dot head so this will give me a
list of the first few record straight sepal length sepal width petal length
petal width and species now let’s see how can we extract only those records
where sepal length is greater than Phi and sepal width is greater than 3 all
right so I’ll start off by giving the name of the data frame and I’ll put in
these braces over here and I’ll give in the first condition so
the first condition is again iris and from this I’d have to select only those
sepal length columns where there is greater than 5 so sepal dot Elian gdh
this value needs to be greater than 5 so I’ve given my first condition after this
I’ll go ahead and give my second condition and this time I’d have to
extract only those records were sepal dot width
let me type this out and this needs to be greater than
three let me also put this inside these braces
over here let me cut this and let me pass it over here I’ll click on run
right so this is our list of values where sepal length is greater than fight
and sepal width is greater than three if I scroll down you will see only those
values were sepal length is greater than 5 and sepal width is greater than 3 so
what we do is we given the first condition where sepal length is greater
than Phi after that we’ll use the and operator and then we give the second
condition which is sepal width is greater than 3 right so of this we again
have this IRS data frame over here and we’ll have to introduce any n values or
null values in the first 10 rows of sepal width column and petal width
columns if you see this original data frame over here you see that these two
columns comprise of some values but then again we’d have to fill the first 10
rows of these two columns with any n values so I’ll start off by luring the
required packages which would be Ponder’s and numb by so input pandas as
PD and the import numpy as NP after this I load the iris dataset so iris equal to
PD dot read CSV and I will pass in the name of the dataset which is iris dot
CSV let me again have a glance at the head
of this dataset so IRAs dot head right so now to introduce any in values
I can use the and B dot and n method so now what I’ll do is I’ll actually create
a duplicate copy of this object so iris one and I will store this data frame
into IRS one now I’ll type in iris dot I lock and I
would want to make changes in the first ten rows and the second column
and the second column right so first in rows and the second column so the index
of the second column would be one and what I’ll do is I will introduce all of
the any n values so and B dot any n let me put an equal to over here now let me
have a glance at the head of this modified data set so iris one dot head
right so we see that this is our original data frame and with the help of
NV dot any n I have introduced any values from actually the first row so
let me actually change this to be 0 here I’ll pick on run so now I have any
values for the first ten records similarly I’ll also go ahead and
introduce any values in the petal length column so over here I just have to change the
index of the column which would be too let me have a glance at the head IRA’s
dart head right so now we’d have to get the number of any n values present in
each column of this and hey instead of him so this is our data frame over here
which comprise of these column so we have each BMI Hyp
and CHL and we see that these three columns over your comprised of any n
values and we’ll have to find the count of the any invaluable um’s
so I’ll start up by loading the pandas dataframe I’ll type in in both pandas as
PD let me just wait till the package is loaded right so now that February is the
package I’d have to load the CSV file with just an Haines dot CSV and for this
I’ll be using PD dot read CSV function and I’ll given the name of the file
which as Ann Haynes dot CSV and I’ll store this in a new object and name that
object to be an hints now if I want to get the count of number of any n values
this is what I’d have to do in hints dot so I have this this any function and
after this I will just print it out let’s see what do we get right so we
just get a bunch of true or false labels so wherever there is an any n value
present we have a true label so over here in the BMI column the first record
this is an any n value this again is an any n value so wherever you see true
values it basically represents all those any and values and if I want the sum of
all of these any n values I just have to type in some and now I
click on run right so we see that each column has no
any invaluable my column has nine na n values Hyp column has eight any n values
and CH l column has ten any n values now we’ll have to open and read a file and
Python so let’s see how can we do that so I actually have this file with the
name sparta and it is present in my D Drive so let me actually copy the path
over here alright so this is just the path which I have to copy so first open
a file in Python I’ll have to use the open function so I’ll just type in F
equals open and thus takes in two parameters the first parameter is just
the path and after the path I will given the name of the file which would be
spoilt r dot txt and the second parameter is the mode which i want to
open this file so i would open this file in the read mode so again I’ll just give
in double quotes and I’ll type in R so R basically means that I am opening this
file in the read mode and I’m storing this in this object F now let me go
ahead and read this of F dot read right so this is the sentence which was
stored in this file this is para and we have successfully
read the sentence so let’s head to the next question so what is the lambda
function and we’d have to create a simple lambda function to add 10 to a
given number well a lambda function is an anonymous function and it can take
any number of arguments but you have only one expression and this is the
syntax of a lambda function so you type in lambda and then you’re given all of
your arguments after that you’ll put in a colon and then you’ll give the
expression so let’s go ahead to Jupiter notebook and clear simple lambda
function to add 10 to a given number right so let me just type in lambda and
I’ll get the name of the variable to be e I’ll give up :
and all I have to do is add 10 to whatever variable is sent into this and
I am naming the function to be let’s say X so this is how we can create a simple
lambda function now I’ll call the function and pass in a number so let’s
say I will pass in 8 now this is returning 18 so all I’m doing is adding
10 to the number which I’m passing into this now again let’s say if I pass 5
into this I’ll get 15 similarly let’s say five powers hundred I’ll get hundred
in 10 so we have successfully created a lambda function which takes in a
parameter and that’s 10 to the given parameter so now we’d have to create a
simple line plot like this where X and y axis values range from 0 to 10 and the
title of the plot is y versus X X label as x axis y ly Billis y axis so simple
line plot and we can create this line plot with the help of the matplotlib
package so let’s quickly run to Jupiter notebook I’ll start by loading the
required packages so I would need the numpy package so I’ll type in import
numpy as and P and I would also need the matplotlib package so I’ll type in from
mat Lord Lib employed
by blood as vld all right so now that the floor is the
required packages let’s go ahead and create the data so our x axis and the y
axis values range from zero to ten so I will name X and I will get the values
with the help of NP dot e range and since the values go from zero to ten
zero then and the step factor as one so let me just print out x over here and
let’s see what do we get right so these are all of the values which I have over
here so 0 1 2 3 4 5 6 7 8 9 right now similarly let me also go ahead and
create the Y values will be the same thing over here it says that instead of
storing the values in X I’ll be storing them in Y so I have my x and y values to
be ready all I have to do is use these zero points and create the line plot so
PLT dot plot and I’ll pass in X comma Y and this is my floor over here now I’ll
also go ahead and add the labels for x-axis y-axis and I’ll also give them
the title p LD dot X label so the level would be x axis similarly p LD dot y
label and the label would be y axis for this of this I’d have to given the title
so the title would be p LD dot title and X versus Y right so we have created our
line plot where the label of x axis the x axis the label of my axis is y axis
and the title of the plot is X versus Y so it’s as simple as that guys so this
is how you can create a simple line plot with the help of the matplotlib package
so now we’d have to create a simple bar plot and we have these foods over here
represented on the x axis so we’ve got apple banana and orange and we’ve got
the cost of the fruits on the y axis so let me start off by lowering the
required library from law clip I’ll be importing by
flawed as PLD of this I just have to create my data so I’ll be creating a
simple dictionary over here and I’ll name this dictionary as data I’ll put in
braces over here and it consists of three fruits which are apple banana and
orange so apple and cost of Apple would be let’s say 50 bucks of that we have
banana and the cost of banana is 20 of that we have orange and the cost of
foreign just 30 all right so now I’ll separate the keys and values from this
so let me get the keys first data dot keys and I’ll get the list of this
I’ll piece this inside this and let’s see I’ll store this in an object named
as names now let me get all of the values similarly
values and I’ll be getting DDOT one use the names I have the values now all I
have to do is make a bot blood and to make a bot blood I’ll be using
PLD dot board and I’d have to pass in the names as well as the values
right so we have successfully created a bar plot and on the x-axis we have the
names and on the y-axis we have the cost in the next question so what do you
understand by your module in Python so when we write everything in our single
page it becomes difficult to track and what is this let’s say if you want to
make a change in a certain place in the project then it would affect the entire
project and may prove to be disastrous and this is where I’ll be using the
concept of modules so instead of writing one big software in one peach you would
have to break it down into parts so a module basically helps us to organize
our Python code now let’s say you want to write a program to create a
calculator now instead of writing all of the features in the same file you can
create separate modules for addition subtraction multiplication and division
now she will perform addition you can invoke the addition module similarly if
you want to perform multiplication you can invoke the multiplication module so
for every single purpose you can have a separate module so that your work
becomes easier so now we’d have to randomize the items awfulest in place in
python so let’s say we have a list which comprised of these elements so let’s say
the first element is Mary and then we have had a little lamp now I’d have to
randomly shuffle all of these elements inside the list and to randomize the
items of the list we can use the shuffle function and the shuffle function is
part of the random library so I’ll type in from random import shuffle
so I have loaded the function now let me go ahead and create the list had little
lamp right now I will just pass him this inside the shuffle function now let
me print an X right so this is in place shuffling inside the list right so
initially the list was really had a little lamb’ or the sequence of the
elements inside this list was merely had a little um and after passing this list
inside the shuffle function the elements changed and the sequence now is a lamb
mary had little so now we’d have to write a program to get the length of the
string of film ology without using the Len function and to get the length of
the string we can just use the for loop so what we’ll do is we’ll start a for
loop and it will iterate through all of the characters in this string and we’ll
get the count of the number of characters present in the string so let
me name the string so it does OPH th PL mo l OG y so let’s hope this is actually
the spelling of Ophthalmology right now let me initialize a counter and set the
value of counter to be equal to zero after this I’ll start the for loop so
for I in E what would basically happiness count equals count plus one
and finally I’ll print out the value of counter so what is happening over here
us initially eyes value is 0 and it will loop through thee all of the characters
of this string which is present in a and so let’s say the loop starts over here
initially eyes value is 0 until enter oh now the count increments by 1 again
it’ll head to the next character in the count again would increment by 1 it’ll
head to the next character and the count would increment by 1 so till the end of
the string will keep counting the number of characters present right and we get
the results over the number of characters present and the string is 13
so now we’d have to replace all the odd numbers in this numpy array 2 minus 1
right so this is an umpire which comprised of the numbers from 0 to 9 and
we’d have to replace all of the odd numbers so one would become minus 1 3
would become minus 1 5 would become minus 1
so wherever odd numbers are present all of those odd numbers would become minus
1 at me both in my library import numpy as NP
of this what I have to do is create my numpy project
so a are R equals NP dot a range and it will go from zero to ten
let me just print out this numpy array over here
this my numpy hurry now let me go ahead and replace all of the odd values with
minus one so what I’ll do is I will basically divide each element with two
and see what is the remainder so arr percentage – and if it is equal to one
so what I’ll do is I will divide zero with two I’ll check the reminder
similarly I will divide one with two and I’ll check the remainder I’ll divide two
with two and I’ll check the remainder so wherever the remainder is equal to one
those elements I’ll be changing it to equal to minus 1 right so first I’ll
divide zero with two and I’ll check what is the remainder and since the remainder
is not equal to one nothing will happen after this I’ll divide one with two and
I’ll check the remainder so if the remainder is equal to one I’ll replace
this with minus one similarly over here if I divide three with two the remainder
which I’ll be getting as one and again this value would be replaced with minus
1 right so the changes have been done now let me Prem this this was my
original array after performing this step over here all of the odd values
have been replaced with minus one one has been replaced with minus 1 3 with
minus 1/5 with minus 1/7 with minus one and nine with minus one now we will have
to perform an operation so that forget the common items between two numbers
this is our first number you’re it this is a second numpy or it now let’s
actually check the common items so if we look closely at these two arrays we see
that two and four are the only two common items present among these two
arrays and I’d want to extract these two right so we have created out arrays over
here this is the first numpy array and I’m storing it in here this is my second
numpy array and I’m storing it in B now to get the common elements I have the N
P dot intersect 1b method so n P dot intersect 1d and I just have to pass in
the two numpy arrays inside this as the parameters so a comma B I’ll pass in
these two and click on run right so I’ve got the
elements present in these stories right so we have a panda series over here and
we’d have to convert each of these elements into title keys so mary had a
little lamb so we see that all of this aren’t small cases now I’d have to
convert all of these elements in Duke title case so let me start off by
loading the pandas library both pandas a speedy now I’ll create the
series Billy dot series and I’ll pass on the values which are basically
mary had a little lamb right so this is done and I’ll store this in let’s say s
er created my series I’ll just print it out
now right so this is my and our series now I’d have to convert all of these
elements into Titleist notice em needs to be capital H needs to be capital e L
and L needs to be capital right and as I’ve already told you will be using the
map method which helps us to replace or substitute values or all of the values
inside a pander series so a CR dot map now inside this I’ll use a lambda
function to convert all of these elements into title keys so let me type
in lambda over here X colon and I just have to convert this into title case
so let me just put in title over you let me click on run right so we have
successfully converted all of these elements into title case now let me
store it back to CR now let me print a CRO here right so all of these elements
have been converted into title case so now we have the same Panda series so
myriad alum now I’d have to calculate the number of characters in each word of
the series so this is one two three and four so there are four characters
present in the word marry there are three characters present in the word
heart this is a single character right so I’d have to find out the total number
of characters present in each words or each of these elements inside this Panda
series single pandas as PV
let me again create the series ser equals P d dot series and I’ll given all
of the elements Mary had little
Lum so now to get the length of each of these words present in this Panda series
I’ll have to use the map method so ser dot map and inside this I will again
create a new lambda function la MBDA a colon and since I have to get the length
I use a length function and I have to get the length of each of these elements
inside the right so we see that the length of the word MIDI is of four
characters in hat there are three characters is a single character and in
little there are six characters and in the word lamb there are four characters
time for next question so again we have this IRS data frame and we have to
change the column name sepal length to s underscore length let me load the
package import pandas a speedy and I’ll also load the file so PD dot read CSV
and the name of the file is aisles dot CSV and I’ll store it back into iris
let me have a glance of the head of the steel frame so it’ll be iris dot head so
we have one of these columns over here and I’d have to change the name of the
sepal dot length column to s length so to rename the columns of Abdera frame I
have the Andaz dot rename method so first I’d have to given the name of the
rear frame which is iris and then I will invoke the rename method now I’d have to
given all of the column names which I’d want to change so I’ll type in columns
over here I’ll create a dictionary and my key would be the name of the column
which I’d water change so I would want to change the name sepal length to be
equal to s underscore length so it’ll be s underscore length so this is how it
goes so iris dot Traynham and the original
column name is Apple dot length and I’d have to change it to s underscore land
and I’ll store it in a new object and in that object to be equal to Iris one now
let me just print out the head of this so iris one dot head
so now we’d have to build a linear regression model on top of this Boston
data frame where the independent variable is this our M column over here
and the dependent variable is this MeV we call them over here and the Train and
that split needs to be equal to 80/20 so this question is basically related to
machine learning with Python where we are implementing our linear regression
model on top of this data set to understand how does this ME DV column
theory with respect to this RM column or in other words a media column is our
dependent variable and our M column is our independent variable and we are
trying to understand how does a MIDI we change with respect to R M so let me
start off by loading the pandas library import pandas as PD right now well go
ahead and also load up our Boston data set so PD dot read and the score CSV
helps me to load up the data set and the name of the reset is Boston dot CSV and
I’m loading this file in this object Boston and then I’ll have a glance at
the head of this so these are all of the columns which are present and this data
frame so I’ve got crimson in this car Snorks RM and so on and ma DV is my
target and my feature is RM or in other words Amedeo is my dependent variable
and RM is my independent variable now I’ll separate the feature and the target
all right so PD dot data frame and so from this
entire Boston data frame I am selecting only the RM column and I am storing it
into the X object similarly from the entire Boston data frame I am selecting
only this MA degree column and I am storing it into this Y object so X would
have the feature values and why would have the target value so now I’ve
extracted the feature and the target now it’s time to divide this dataset into
training and testing set so the Train test plate needs to be 80 20 or in other
words 80% of all of the records would be present in the training set and 20
percent of all of the records would be present in the testing set I
do this I’d need the Train displayed from SK learn more selection so I’ll
dive from a scale or not model selection import train to split and this method
takes in these parameters so first I’d have to pass in the features and then
I’d have to pass in the target so X comma Y and then I’d have to give in the
test size or test sizes zero point two zero so this again means that now it
that said would comprise 20% records and the train set would compare the 80% of
the records and the values would be stored in extreme X just white rain and
whitest so X train would comprise of all of the training values or all of the
training records for the features and X test as basically the test set for the
features white rain is the Train set for the target and whitest is the test set
for the target so we have our training and testing sets ready let me click on
run over here right now it’s finally time to build the model on top of the
train set so from a scale or not in your model I will import the linear
regression and I create an instance of this so I’ll name that instance to be
regressor and I will fit this model on top of extreme and white rink or in
other words I am filling the model on top of the train set all right so now
that will fit the model it’s finally time to predict the values on top of the
test set and to break the values I’ll use regressor dot predict and the
parameter which I’m passing inside this as X underscore test and I’ll store this
in Y underscore bread now once you predict the values I have to find out
the root mean square error so I’ll import metrics from SK learn and this is
how I get the root mean squared error so metrics dot mean squared error and this
takes in two parameters whitest and vibrate so whitest comprised of all of
the actual values and wipe red compressor for all of the predicted
values and I will pass these two inside mean squared error now when I do this
I’ll get only the mean square error but I wonder root mean squared error so I’ll
use NP dot square root so I would also have to import an empire
library over here I’ll type in import numpy as an B now I click on run so now
we’ve arrived at our final interview question and we’d have to build a
decision tree classifier on top of this I resign of him where the dependent
variable is the species column and the independent variables are the rest of
the column sub sepal length sepal width petal length and petal width would be
the independent variables and your species column is your dependent
variable and the Train does split 7030 so I’ll start by loading the requisite
packages which are numpy and pandas so important umpires NP and import pandas
are speedy then officers I’ll load my dataset so PD
dot read underscore CSV I’ll pass in the file name is dot CSV and I’ll store this
in the iris object and we have a glance at the head of this dataset so these are
all the columns present on this data frame we’ve got sepal length sepal width
petal length petal width and the species column now all of this the species
column is our dependent variable and these four columns the numerical columns
are independent variables so now I’ll go ahead and separate the features and the
target variable so these are all of my features these first four columns so
I’ll just extract sepal length sepal width petal length and petal width from
the situs data frame and I’ll store that into this X object similarly I’ll
extract only the species column from the entire Rider 0 frame and I’ll store it
into y object so I have my features and the target ready now it’s time to divide
this entire data frame in to train and test plate so I’d have to input
trained pest split from a scale or not model selection and the stakes in these
parameters first parameter are the features second parameter is the object
which comprise of the target label and the test size is zero point three zero
so 30% of the records would go into the test set and the rest 70 percent of the
records would go into the training set and I am storing the results into
extreme X test while train and Y test so X train is the training set for the
features extras is a test set for the features white rain is the tray
set for the target and whitest is the test set for the target now we’ll import
the season tree classifier from SK learn dot T so I will go ahead and create an
instance of this decision tree classifier and I’ll name that instance
to be classifier and I will fit this classifier on top of the training set so
classifier dot fit and I’ll pass in X train and why train inside this so we
have successfully fit the model on top of the train set now we’ll go ahead and
break the values on top of the test set so classify dot predict so I’ll store
the result in to wipe read off this will calculate some metrics so we’ll get the
confusion matrix and we’ll also get the accuracy score right so this is my
confusion matrix and this is the accuracy so the left diagonals which you
see in this confusion matrix all of these are the values which have been
predicted or classified correctly so this first row represents the species of
setosa second row those species of versicolor and the third row the species
of virginica right so see that all of the species of setosa have been
classified correctly when it comes to versicolor sixteen of them have been
classified correctly and two of them have been classified incorrectly and
when it comes to words indica 13 of them have been classified correctly and two
of them have been classified incorrectly so to get the accuracy we’d have to add
12 plus 16 plus 13 buy all of the values so let me just do that 12 plus 16 plus
13 divided by well plus 16 plus 13 plus 2 plus 2
so the accuracy is the same and it comes out to be 90 1.11 so I hope this session
was informative for you guys and if you have any doubts do comment below we’ll
help you out thank you

9 thoughts on “Python Interview Questions | Python Tutorial | Intellipaat

  • Guys, which technology you want to learn from Intellipaat? Comment down below and let us know so we can create in depth video tutorials for you.:)

  • 🔥🔥🔥Intellipaat's Python online training course: https://intellipaat.com/python-certification-training-online/🔥🔥🔥

  • 📝Following topics are covered in this video:

    Python Job Trend – 00:38

    Basic Questions – 1:10

    Questions on OOPS – 5:27

    Questions on NumPy – 16:02

    Questions on Pandas – 22:17

    File Handling in Python – 31:11

    Lambda Function in Python – 32:05

    Questions on Matplotlib – 33:23

    Module in Python – 37:47

    Random Questions – 38:47

    Machine Learning with Python – 49:16

  • May i know answer of these two question:

    what command is used to output text from both the python shell and within a python module?

    when using the python shell and code block, what triggers the interpreter to begin evaluating a block of code?

  • Your Pronunciation is awesome , perfectly audible
    Algorithms in Python !! If possible , please make a video on this Topic

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *