120 Python Interview Questions and Answers in 2021 - You Should Know
120 Python Interview Questions and Answers in 2021 - You Should Know
Python Interview
EXPLORE PROGRAMS
Questions and Answers
ARTIFICIAL INTELLIGENCE DATA SCIENCE
in BUSINESS
2021ANALYTICS
By Great Learning Team - Mar 5, 2021
CLOUD COMPUTING
MORE
Interviewing for Python can be quite intimidating. If you are appearing for a technical round
of interview for Python, here’s a list of the top 101 interview questions with answers to help
you prepare. The first set of questions and answers are curated for freshers while the second
set is designed for advanced users. These questions cover all the basic applications of Python
and will showcase your expertise in the subject. The questions are divided into groups such as
basic, intermediate, and advanced questions.
Do check out our Free Course on Python Interview Questions on Great Learning Academy.
It covers all the basic and advanced level questions.
S.No- Questions
1. #What are the key features of Python?
2. #What are Keywords in Python?
3. #What are Literals in Python and explain about different Literals?
4. #How can you concatenate two tuples?
5. #What are functions in Python?
6. #How can you initialize a 5*5 numpy array with only zeroes?
7. #What is Pandas?
8. #What are dataframes?
9 #What is a Pandas Series?
10. #What is Pandas groupby?
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 1/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
Here is a video which talks about the Python Interview Questions and Answers in detail
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
Python is one of the most popular programming languages used by data scientists and AIML
MORE
professionals. This popularity is due to the following key features of Python:
Keywords in Python are reserved words which are used as identifiers, function name or
variable name. They help define the structure and syntax of the language.
There are a total of 33 keywords in Python 3.7 which can change in the next version, i.e.,
Python 3.8. A list of all the keywords is provided below:
Keywords in Python
break except
Literals in Python refer to the data that is given in a variable or constant. Python has various
kinds of literals including:
Solution ->
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
tup1 = (1,”a”,True)
MORE
tup2 = (4,5,6)
Concatenation of tuples means that we are adding the elements of one tuple at the end of
another tuple.
All you have to do is, use the ‘+’ operator between the two tuples and you’ll get the
concatenated result.
Ans: Functions in Python refer to blocks that have organised, and reusable codes to perform
single, and related events. Functions are important to create better modularity for applications
which reuse high degree of coding. Python has a number of built-in functions like print().
However, it also allows you to create user-defined functions.
6. How can you initialize a 5*5 numpy array with only zeroes?
Solution ->
Use np.zeros() and pass in the dimensions inside it. Since, we want a 5*5 matrix, we will pass
(5,5) inside the .zeros() method.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 3/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
7. What is Pandas?
Pandas is an open source python library which has a very rich set of data structures for data
based operations. Pandas with it’s cool features fits in every role of data operation, whether it
be academics or solving complex business problems. Pandas can deal with a large variety of
files and is one of the most important tools to have a grip on.
A pandas dataframe is a data structure in pandas which is mutable. Pandas has support for
heterogeneous data which is arranged across two axes.( rows and columns).
Import pandas as pd
df=p.read_csv(“mydata.csv”)
Here df is a pandas data frame. read_csv() is used to read a comma delimited file as a
dataframe in pandas.
Series is a one dimensional pandas data structure which can data of almost any type. It
resembles an excel column. It supports multiple operations and is used for single dimensional
data operations.
A pandas groupby is a feature supported by pandas which is used to split and group an
object. Like the sql/mysql/oracle groupby it used to group data by classes, entities which can
be further used for aggregation. A dataframe can be grouped by one or more columns.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 4/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
A dictionary can be directly passed as an argument to the DataFrame() function to create the
data frame.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 5/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
Two different data frames can be stacked either horizontally or vertically by the concat(),
append() and join() functions in pandas.
Concat works best when the dataframes have the same columns and can be used for
concatenation of data having similar fields and is basically vertical stacking of dataframes
into a single dataframe.
Join is used when we need to extract data from different dataframes which are having one or
more common columns. The stacking is horizontal in this case.
Before going through the questions, here’s a quick video to help you refresh your memory on
Python.
Pandas has a left join, inner join, right join and an outer join.
Merging depends on the type and fields of different dataframes being merged. If data is
having similar fields data is merged along axis 0 else they are merged along axis 1.
16. Give the below dataframe drop all rows having Nan.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 6/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
By using the head(5) function we can get the top five entries of a dataframe. By default
df.head() returns the top 5 rows. To get the top n rows df.head(n) will be used.
By using tail(5) function we can get the top five entries of a dataframe. By default df.tail()
returns the top 5 rows. To get the last n rows df.tail(n) will be used.
19. How to fetch a data entry from a pandas dataframe using a given
value in index?
20. What are comments and how can you add comments in Python?
Comments in Python refer to a piece of text intended for information. It is especially relevant
when more than one person works on a set of codes. It can be used to analyse code, leave
feedback, and debug it. There are two types of comments which includes:
1. Single-line comment
2. Multiple-line comment
“””Note
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 7/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
Note
CLOUD COMPUTING
21. What is the difference between list and tuples in Python?
MORE
Lists are mutable, but tuples are immutable.
Example
d={“a”:1,”b”:2}
23. Find out the mean, median and standard deviation of this numpy
array -> np.array([1,5,3,100,4,48])
A classifier is used to predict the class of any data point. Classifiers are special hypotheses
that are used to assign class labels to any particular data points. A classifier often uses
training data to understand the relation between input variables and the class. Classification is
a method used in supervised learning in Machine Learning.
All the upper cases in a string can be converted into lowercase by using the method:
string.lower()
o/p: [1, 2, 3]
We can use the capitalize() function to capitalize the first character of a string. If the first
character is already in capital then it returns the original string.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 8/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
28. How can you insert an element at a given index in Python?
MORE
Python has an inbuilt function called the insert() function.
There are various methods to remove duplicate elements from a list. But, the most common
one is, converting the list into a set by using the set() function and using the list() function to
convert it back to a list, if required. ex: list0 = [2, 6, 4, 7, 4, 6, 7, 2]
list1 = list(set(list0)) print (“The list without duplicates : ” + str(list1)) o/p: The list without
duplicates : [2, 4, 6, 7]
Recursion is a function calling itself one or more times in it body. One very important
condition a recursive function should have to be used in a program is, it should terminate,
else there would be a problem of an infinite loop.
List comprehensions are used for transforming one list into another list. Elements can be
conditionally included in the new list and each element can be transformed as needed. It
consists of an expression leading a for clause, enclosed in brackets. for ex: list = [i for i in
range(1000)]
print list
The bytes() function returns a bytes object. It is used to convert objects into bytes objects, or
create empty bytes object of the specified size.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 9/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
34. What is the ‘with statement’?
MORE
“with” statement in python is used in exception handling. A file can be opened and closed
while executing a block of code, containing the “with” statement., without using the close()
function. It essentially makes the code much more easy to read.
The map() function in Python is used for applying a function on all elements of a specified
iterable. It consists of two parameters, function and iterable. The function is taken as an
argument and then applied to all the elements of an iterable(passed as the second argument).
An object list is returned as a result.
def add(n):
print(list(res))
o/p: 30,50,70,90
_init_ methodology is a reserved method in Python aka constructor in OOP. When an object
is created from a class and _init_ methodolgy is called to acess the class attributes.
The two static analysis tool used to find bugs in Python are: Pychecker and Pylint. Pychecker
detects bugs from the source code and warns about its style and complexity.While, Pylint
checks whether the module matches upto a coding standard.
One major difference between a tuple and a dictionary is that dictionary is mutable while a
tuple is not. Meaning the content of a dictionary can be changed without changing it’s
identity, but in tuple that’s not possible.
Pass is a statentemen which does nothing when executed. In other words it is a Null
statement. This statement is not ignored by the interpreter, but the statement results in no
operation. It is used when you do not want any command to execute but a statement is
required.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 10/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
Modules are the way to structure a program. Each Python program file is a module, importing
other attributes and objects. The folder of a program is a package of modules. A package can
have modules or subfolders.
In Python the object() function returns an empty object. New properties or methods cannot be
added to this object.
NumPy stands for Numerical Python while SciPy stands for Scientific Python. NumPy is the
basic library for defining arrays and simple mathematica problems, while SciPy is used for
more complex problems like numerical integration and optimization and machine learning
and so on.
len() is used to determine the length of a string, a list, an array, and so on. ex: str =
“greatlearning”
print(len(str))
o/p: 13
Encapsulation means binding the code and the data together. A Python class for example.
type() is a built-in method which either returns the type of the object or returns a new type
object based on the arguments passed.
ex: a = 100
type(a)
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 11/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
o/p: int
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
Split fuction is used to split a string into shorter string using defined seperatos. letters = (” A,
MORE
B, C”)
n = text.split(“,”)
print(n)
Boolean: The Boolean data type is a data type that has one of two possible values i.e. True or
False. Note that ‘T’ and ‘F’ are capital letters.
String: A string value is a collection of one or more characters put in single, double or triple
quotes.
List: A list object is an ordered collection of one or more data items which can be of different
types, put in square brackets. A list is mutable and thus can be modified, we can add, edit or
delete individual elements in a list.
Frozen set: They are like a set but immutable, which means we cannot modify their values
once they are created.
Dictionary: A dictionary object is unordered in which there is a key associated with each
value and we can access each value through its key. A collection of such pairs is enclosed in
curly brackets. For example {‘First Name’ : ’Tom’ , ’last name’ : ’Hardy’} Note that Number
values, strings, and tuple are immutable while as List or Dictionary object are mutable.
Ans. Python docstrings are the string literals enclosed in triple quotes that appear right after
the definition of a function, method, class, or module. These are generally used to describe
the functionality of a particular function, method, class, or module. We can access these
docstrings using the __doc__ attribute. Here is an example:
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 12/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
<code>def square(n): '''Takes in a number n, returns the square of n''' return n**2 print(s
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
CLOUD COMPUTING
Ouput: Takes in a number n, returns the square of n
MORE
grouby() in pandas can be used with multiple aggregate functions. Some of which are
sum(),mean(), count(),std().
Data is divided into groups based on categories and then the data in these individual groups
can be aggregated by the aforementioned functions.
If there are two columns with the same name then both columns get copied to the new
dataframe.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 13/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 14/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
7. Given the above dataset find the min max and average
salary of a player collegewise and teamwise.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 15/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
<code>from functools import reduce sequences = [5, 8, 10, 20, 50, 100] sum = reduce (lambd
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 16/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
print (str.strip())
o/p: greatlearning
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 17/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
Memory management in python comprises of a private heap containing all objects and data
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE
stucture. The heap is managed by the interpreter and the programmer does not BUSINESS
have acessANALYTICS
to it
at all. The Python memory manger does all the memory allocation. Moreover, there is an
CLOUD COMPUTING
inbuilt garbage collector that recycles and frees memory for the heap space.
MORE
Here smart_divide is a decorator function that is used to add functionality to simple divide
function.
Take up a data science course and power ahead in your career today!
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 18/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
From this dataset, how will you make a bar-plot for the top 5 states having maximum
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
confirmed cases as of 17=07-2020?
sol:
CLOUD COMPUTING
<code>#keeping only required columns df = df[[‘Date’,
MORE‘State/UnionTerritory’,’Cured’,’Dea
Code explanation:
We start off by taking only the required columns with this command:
df = df[[‘Date’, ‘State/UnionTerritory’,’Cured’,’Deaths’,’Confirmed’]]
After that, we extract only those records, where the date is equal to 17th July:
Then, we go ahead and select the top 5 states with maximum no. of covide cases:
max_confirmed_cases=today.sort_values(by=”confirmed”,ascending=False)
max_confirmed_cases
top_states_confirmed=max_confirmed_cases[0:5]
sns.set(rc={‘figure.figsize’:(15,10)})
sns.barplot(x=”state”,y=”confirmed”,data=top_states_confirmed,hue=”state”)
plt.show()
Here, we are using seaborn library to make the bar-plot. “State” column is mapped onto the
x-axis and “confirmed” column is mapped onto the y-axis. The color of the bars is being
determined by the “state” column.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 19/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
How can you make a bar-plot for the top-5 states with the most amount of deaths?
Sol:
<code>max_death_cases=today.sort_values(by=”deaths”,ascending=False) max_death_case
Code Explanation:
We start off by sorting our dataframe in descending order w.r.t the “deaths” column:
max_death_cases=today.sort_values(by=”deaths”,ascending=False)
Max_death_cases
Then, we go ahead and make the bar-plot with the help of seaborn library:
sns.set(rc={‘figure.figsize’:(15,10)})
sns.barplot(x=”state”,y=”deaths”,data=top_states_death,hue=”state”)
plt.show()
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 20/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
Here, we are mapping “state” column onto the x-axis and “deaths” column onto the y-axis.
CLOUD COMPUTING
3. From this covid-19 dataset:
MORE
How can you make a line plot indicating the confirmed cases with respect to date?
Sol:
Code Explanation:
We start off by extracting all the records where the state is equal to “Maharashtra”:
sns.set(rc={‘figure.figsize’:(15,10)})
sns.lineplot(x=”date”,y=”confirmed”,data=maha,color=”g”)
plt.show()
Here, we map the “date” column onto the x-axis and “confirmed” column onto y-axis.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 21/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
MORE
How will you implement a linear regression algorithm with “date” as independent variable
and “confirmed” as dependent variable. That is you have to predict the number of confirmed
cases w.r.t date.
Sol:
Code solution:
maha[‘date’]=maha[‘date’].map(dt.datetime.toordinal)
This is done because we cannot build the linear regression algorithm on top of the date
column.
Then, we go ahead and divide the dataset into train and test sets:
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)
lr = LinearRegression()
lr.fit(np.array(x_train).reshape(-1,1),np.array(y_train).reshape(-1,1))
lr.predict(np.array([[737630]]))
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 22/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
Build a keras sequential model to find out how many customers will churn out on the
basis of tenure of customer?
Sol:
<code>from keras.models import Sequential from keras.layers import Dense model = Seque
Code explanation:
model = Sequential()
model.add(Dense(8, activation=’relu’))
model.add(Dense(1, activation=’sigmoid’))
y_pred = model.predict_classes(x_test)
confusion_matrix(y_test,y_pred)
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 23/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
Build a decision tree classification model, where dependent variable is “Species” and
independent variable is “Sepal.Length”.
Sol:
(22+7+9)/(22+2+0+7+7+11+1+1+9)
Code explanation:
y = iris[[‘Species’]]
x = iris[[‘Sepal.Length’]]
Then, we go ahead and divide the data into train and test set:
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.4)
dtc = DecisionTreeClassifier()
dtc.fit(x_train,y_train)
y_pred=dtc.predict(x_test)
confusion_matrix(y_test,y_pred)
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 24/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
(22+7+9)/(22+2+0+7+7+11+1+1+9)
MORE
Build a decision tree regression model where the independent variable is “petal length” and
dependent variable is “Sepal length”.
Sol:
Sol:
<code>import sys import time from bs4 import BeautifulSoup import requests import pand
You also have to build two plots on “Sampling Distribution of bmi” and “Population
distribution of bmi”.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 25/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
Sol:
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
MORE
Code Explanation:
df = pd.read_csv(‘insurance.csv’)
Data
N_samples
Sample_size
Min_value
Max_value
import pandas as pd
import numpy as np
Then, we go ahead and create the first sub-plot for “Sampling distribution of bmi”:
plt.subplot(1,2,1)
sns.distplot(c.Mean)
plt.xlabel(‘data’)
plt.ylabel(‘freq’)
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 26/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
plt.subplot(1,2,2)
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
sns.distplot(data)
CLOUD COMPUTING
plt.xlabel(‘data’)
plt.ylabel(‘freq’)
plt.show()
<code>import numpy as np import pylab import scipy.stats as stats from matplotlib import
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 27/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
Sol:
Code solution:
import pandas as pd
iris = pd.read_csv(“iris.csv”)
iris.head()
Then, we will go ahead and extract the independent variables and dependent variable:
x = iris[[‘Sepal.Width’,’Petal.Length’,’Petal.Width’]]
y = iris[[‘Sepal.Length’]]
Following which, we divide the data into train and test sets:
lr = LinearRegression()
lr.fit(x_train, y_train)
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 28/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
y_pred = lr.predict(x_test)
CLOUD COMPUTING
mean_squared_error(y_test, y_pred)
Find the percentage of transactions which are fraudulent and not fraudulent. Also build a
logistic regression model, to find out if the transaction is fraudulent or not.
Sol:
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 29/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
Sol:
<code>import numpy as np # linear algebra import pandas as pd # data processing, CSV file
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 30/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
# However we want to see correlation in graphical representation so below is function for that
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 31/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
def __init__(self):
self.x=0
self.y=0
Example
class Node(object):
def __init__(self):
self.x=0
self.y=0
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 32/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
4. What is multi-level inheritance? MORE
Give an example for
multi-level inheritance?
<code>If class A inherits from B and C inherits from A it’s called multilevel inheritance. clas
We can use the min() function on top of the tuple to find out the minimum value present in
the tuple:
Analogous to the min() function is the max() function, which will help us to find out the
maximum value present in the tuple:
We will start off by creating a tuple which will comprise of the indices of elements which we
want to access:
Then, we will use a for loop to go through the index values and print them out:
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 33/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
Below is the entire code for the process: MORE
Give in the name of the key inside the parenthesis and assign it a new value.
You can use the intersection() function to find the common elements between the two sets:
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 34/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
We see that the common elements between the two sets MORE 6.
are 5 &
We start off by initializing two variables ‘i’ and ‘n’. ‘i’ is initialized to 1 and ‘n’ is initialized
to ‘2’.
Inside the while loop, since the ‘i’ value goes from 1 to 10, the loop iterates 10 times.
Then, ‘i’ value is incremented and n*i becomes 2*2. We go ahead and print it out.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 35/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
Here, we start off by creating a method, with the name ‘even_odd()’. This function takes a
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE
single parameter and prints out if the number taken is even DATA SCIENCE
or odd. BUSINESS ANALYTICS
CLOUD COMPUTING
Now, let’s invoke the function:
MORE
We see that, when 5 is passed as a parameter into the function, we get the output -> ‘5 is
odd’.
We start off by taking an input which is stored in ‘num’. Then, we check if ‘num’ is less than
zero and if it is actually less than 0, we print out ‘Sorry, factorial does not exist for negative
numbers’.
After that, we check,if ‘num’ is equal to zero, and it that’s the case, we print out ‘The
factorial of 0 is 1’.
On the other hand, if ‘num’ is greater than 1, we enter the for loop and calculate the factorial
of the number.
Below is the code to Check whether the given number is palindrome or not:
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 36/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
We will start off by taking an input and store it in ‘n’ and make a duplicate of it in ‘temp’. We
will also initialize another variable ‘rev’ to 0.
Then, we will enter a while loop which will go on until ‘n’ becomes 0.
Inside the loop, we will start off by dividing ‘n’ with 10 and then store the remainder in ‘dig’.
Then, we will multiply ‘rev’ with 10 and then add ‘dig’ to it. This result will be stored back
in ‘rev’.
Going ahead, we will divide ‘n’ by 10 and store the result back in ‘n’
Once the for loop ends, we will compare the values of ‘rev’ and ‘temp’. If they are equal, we
will print ‘The number is a palindrome’, else we will print ‘The number isn’t a palindrome’.
22
333
4444
55555
Solution ->
We are solving the problem with the help of nested for loop. We will have an outer for loop,
which goes from 1 to 5. Then, we have an inner for loop, which would print the respective
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 37/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
numbers.
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
11. Pattern
CLOUD questions.
COMPUTING Print the following pattern
#
MORE
# #
# # #
# # # #
#####
Solution –>
<code>def pattern_1(num): # outer loop handles the number of rows # inner loop h
# #
# # #
# # # #
#####
Solution –>
01
012
0 1 2 3
01234
Solution –>
23
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 38/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
456
7 8EXPLORE
9 10
PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
11 12 13 14 15
CLOUD COMPUTING
Solution –>
MORE
BB
CCC
DDDD
Solution –>
BC
DEF
GHIJ
KLMNO
PQRSTU
Solution –>
# #
# # #
# # # #
# # # # #
Solution –>
<code>Code: def pattern 7(num): # number of spaces is a function of the input num
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 39/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
p _ ( ) p p
18. Given
CLOUD the below dataframes form a single dataframe
COMPUTING
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 40/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
CLOUD COMPUTING
MORE
Great Learning offers extensive courses on Artificial Intelligence and Machine Learning.
Upskilling in this domain can land you the job of your dreams.
Now that you’re ready for a Python Interview in terms of technical skills, you must be
wondering how to stand out from the crowd so that you’re the selected candidate. You must
be able to show that you can write clean production codes and have knowledge about the
libraries and tools required. If you’ve worked on any prior projects, then showcasing these
projects in your interview will also help you stand out from the rest of the crowd.
To prepare for a Python Interview, you must know syntax, key-words, functions and classes,
data types, basic coding, and exception handling. Having basic knowledge regarding all the
libraries, IDE’s used and reading blogs related to Python Tutorial’s will help you going
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 41/42
6/15/2021 120 Python Interview Questions and Answers in 2021 - You Should Know
forward. Showcase your example projects, brush up your basic skills about algorithms, data
EXPLORE PROGRAMS ARTIFICIAL INTELLIGENCE DATA SCIENCE BUSINESS ANALYTICS
structures. This will help you stay prepared.
CLOUD COMPUTING
Ques 3. Are Python coding interviews very difficult?
MORE
The difficulty level of a Python Interview will vary depending on the role you are applying
for, the company, their requirements, and your skill and knowledge/work experience. If
you’re a beginner in the field and are not yet confident about your coding ability, you may
feel that the interview is difficult. Being prepared and knowing what type of questions to
expect will help you prepare well and ace the interview.
Having adequate knowledge regarding Object Relational Mapper (ORM) libraries, Django or
Flask, unit testing and debugging skills, fundamental design principles behind a scalable
application, Python packages such as NumPy, Scikit learn are extremely important for you to
clear a coding interview. You can showcase your previous work experience or coding ability
through projects, this acts as an added advantage.
If you wish to upskill, taking up a certificate course will help you gain the required
knowledge. You can take up a python programming course and kick-start your career in
Python.
https://www.mygreatlearning.com/blog/python-interview-questions/?highlight=interview 42/42