Python Interview Questions
Python Interview Questions
Question& Answers.
Python Interview Questions for Freshers
This section on Python Interview Questions for freshers covers 70+
questions that are commonly asked during the interview process. As a
fresher, you may be new to the interview process; however, learning these
questions will help you answer the interviewer confidently and ace your
upcoming interview.
1. What is Python?
Python was created and first released in 1991 by Guido van Rossum. It is a
high-level, general-purpose programming language emphasizing code
readability and providing easy-to-use syntax. Several developers and
programmers prefer using Python for their programming needs due to its
simplicity. After 30 years, Van Rossum stepped down as the leader of the
community in 2018.
2. Why Python?
2|Page
To Install Python, go to Anaconda.org and click on “Download Anaconda”.
Here, you can download the latest version of Python. After Python is
installed, it is a pretty straightforward process. The next step is to power up
an IDE and start coding in Python. If you wish to learn more about the
process, check out this Python Tutorial. Check out How to install python.
– Web Applications
3|Page
beautiful soup libraries, Feedparser libraries, and other internet protocols.
Instagram uses Django, a Python web framework.
The Graphical User Interface (GUI) is a user interface that allows for easy
interaction with any programme. Python contains the Tk GUI framework for
creating user interfaces.
– Console-based Application
Python has a number of free libraries and modules that help in the
creation of command-line applications. To read and write, the appropriate
IO libraries are used. It has capabilities for processing parameters and
generating console help text built-in. There are additional advanced
libraries that may be used to create standalone console applications.
– Software Development
4|Page
language for artificial intelligence and machine learning applications. It
has a number of scientific and mathematical libraries that make doing
difficult computations simple.
• SciPy
• Scikit learn
• NumPy
• Pandas
• Matplotlib
– Business Applications
Standard apps are not the same as business applications. This type of
program necessitates a lot of scalability and readability, which Python
gives.
– 3D CAD Applications
5|Page
component. The following features in Python can be used to develop a 3D
CAD application:
• Fandango (Popular)
• CAMVOX
• HeeksCNC
• AnyCAD
• RCAM
– Enterprise Applications
Python has a lot of libraries for working with pictures. The picture can be
altered to our specifications. OpenCV, Pillow, and SimpleITK are all image
processing libraries present in python. In this topic, we’ve covered a wide
range of applications in which Python plays a critical part in their
development. We’ll study more about Python principles in the upcoming
tutorial.
6|Page
• The language that is dynamically typed (No need to mention
data type based on the value assigned, it takes data type)
• Object-oriented programming language
• Interactive and transportable
• Ideal for prototypes since it allows you to add additional features
with minimal code.
• Highly Effective
• Internet of Things (IoT) Possibilities
• Portable Interpreted Language across Operating Systems
• Since it is an interpreted language it executes any code line by
line and throws an error if it finds something missing.
• Python is free to use and has a large open-source community.
• Python has a lot of support for libraries that provide numerous
functions for doing any task at hand.
• One of the best features of Python is its portability: it can and
does run on any platform without having to change the
requirements.
• Provides a lot of functionality in lesser lines of code compared to
other programming languages like Java, C++, etc.
6. What are the key features of Python?
7|Page
point numbers, Booleans, and character strings are some of the most
common forms of literal. Python supports the following literals:
Boolean Literals: True or False, which signify ‘1’ and ‘0,’ respectively, can be
assigned to them.
Special Literals: It’s used to categorize fields that have not been
generated. ‘None’ is the value that is used to represent it.
8|Page
Python is an interpreted, interactive, object-oriented programming
language. Classes, modules, exceptions, dynamic typing, and extremely
high-level dynamic data types are all present.
An interpreter takes your code and executes (does) the actions you
provide, produces the variables you specify, and performs a lot of
behindthe-scenes work to ensure it works smoothly or warns you about
issues.
9|Page
Python is known as an interpreted language because it uses an interpreter
to convert the code you write into a language that your computer’s
processor can understand. You will later download and utilise the Python
interpreter to be able to create Python code and execute it on your own
computer when working on a project.
10|Page
11. What is namespace in Python?
Global Namespace: Names from various imported modules that you are
utilizing in a project are stored in this namespace. It’s formed when the
module is added to the project and lasts till the script is completed.
11|Page
13. What are Python modules?
Local variables are declared inside a function and have a scope that is
confined to that function alone, whereas global variables are defined
outside of any function and have a global scope. To put it another way,
local variables are only available within the function in which they were
created, but global variables are accessible across the programme and
throughout each function.
Local Variables
Local variables are variables that are created within a function and are
exclusive to that function. Outside of the function, it can’t be accessed.
Global Variables
Global variables are variables that are defined outside of any function and
are available throughout the programme, that is, both inside and outside
of each function.
12|Page
Benefits:
13|Page
Flask is a “micro framework” designed for smaller applications with less
requirements. Pyramid and Django are both geared at larger projects, but
they approach extension and flexibility in different ways.
Django includes an ORM by default, but Pyramid and Flask provide the
developer control over how (and whether) their data is stored.
SQLAlchemy is the most popular ORM for non-Django web apps, but there
are lots of alternative options, ranging from DynamoDB and MongoDB to
simple local persistence like LevelDB or regular SQLite. Pyramid is designed
to work with any sort of persistence layer, even those that have yet to be
conceived.
It includes an ORM. It provides flexibility and the It does not require external
right tools. libraries.
14|Page
1. Model
2. View
The View is the user interface, or what you see when you visit a website in
your browser. HTML/CSS/Javascript files are used to represent them.
3. Controller
The Controller is the link between the view and the model, and it is
responsible for transferring data from the model to the view.
Your application will revolve around the model using MVC, either
displaying or altering it.
Think of scope as the father of a family; every object works within a scope.
A formal definition would be this is a block of code under which no matter
how many objects you declare they remain relevant. A few examples of
the same are given below:
def harshit_fun():
y = 100
print (y)
15|Page
harshit_func()
100
• Global Scope: When a variable is created inside the main body of
python code, it is called the global scope. The best part about
16|Page
global scope is they are accessible within any part of the python
code from any scope be it global or local. Example:
y = 100
def harshit_func():
print (y)
harshit_func()
print (y)
• Nested Function: This is also known as a function inside a function,
as stated in the example above in local scope variable y is not
available outside the function but within any function inside
another function. Example:
def first_func():
y = 100
def nested_func1():
print(y)
nested_func1()
first_func()
• Module Level Scope: This essentially refers to the global objects of
the current module accessible within the program.
• Outermost Scope: This is a reference to all the built-in names that
you can call in the program.
20. List the common built-in data types in Python?
17|Page
List: We have already seen a bit about lists, to put a formal definition a list
is an ordered sequence of items that are mutable, also the elements
inside lists can belong to different data types.
Example:
Tuples: This too is an ordered sequence of elements but unlike lists tuples
are immutable meaning it cannot be changed once declared.
Example:
Example:
“Hi, I work at great learning”
Sets: Sets are basically collections of unique items where order is not
uniform.
Example:
set = {1,2,3}
Dictionary: A dictionary always stores values in key and value pairs where
each value can be accessed by its particular key.
Example:
Boolean: There are only two boolean values: True and False
18|Page
21. What are global, protected, and private attributes in Python?
The attributes of a class are also called variables. There are three access
modifiers in Python for variables, namely
def price(self):
return m2
Sam_m = Mobile()
print(Sam_m.m1)
19|Page
Keywords in Python are reserved words that are used as identifiers,
function names, or variable names. 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:
as elif if or yield
break except
List and tuple are data structures in Python that may store one or more
objects or values. Using square brackets, you may build a list to hold
numerous objects in one variable. Tuples, like arrays, may hold numerous
items in a single variable and are defined with parenthesis.
Lists Tuples
20|Page
Lists are mutable. Tuples are immutable.
The impacts of iterations are Time Consuming. Iterations have the effect of making
things go faster.
The list is more convenient for actions like The items may be accessed using the
insertion and deletion. tuple data type.
There are numerous techniques built into lists. There aren’t many built-in methods in
Tuple.
Changes and faults that are unexpected are more It is difficult to take place in a tuple.
likely to occur.
They consume a lot of memory given the nature They consume less memory
of this data structure
21|Page
24. How can you concatenate two tuples?
Code:
tup1=(1,"a",True)
tup2=(4,5,6)
tup1+tup2
All you have to do is, use the ‘+’ operator between the two tuples and you’ll
get the concatenated result.
Code:
tup1=(1,"a",True)
tup2=(4,5,6)
tup2+tup1
Ans: Functions in Python refer to blocks that have organized, and reusable
codes to perform single, and related events. Functions are important to
create better modularity for applications that reuse a high degree of
coding. Python has a number of built-in functions like print(). However, it
also allows you to create user-defined functions.
22|Page
26. How can you initialize a 5*5 numpy array with only
zeroes?We will be using the .zeros() method.
import numpy as np
n1=np.zeros((5,5))
n1
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.
Pandas is an open-source python library that has a very rich set of data
structures for data-based operations. Pandas with their cool features fit 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 are
one of the most important tools to have a grip on.
23|Page
12 Import pandas as pddf=p.read_csv(“mydata.csv”)
Code:
import pandas as pd
data=["1",2,"three",4.0]
series=pd.Series(data)
print(series)
print(type(series))
Code:
df = pd.DataFrame({'Vehicle':['Etios','Lamborghini','Apache200','Pulsar200'],
'Type':["car","car","motorcycle","motorcycle"]})
24|Page
df
df.groupby('Type').count()
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
df["cars"]=cars
df["bikes"]=bikes
df
Code:
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
25|Page
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
df
Concat works best when the data frames 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.
Before going through the questions, here’s a quick video to help you
refresh your memory on Python.
Pandas have a left join, inner join, right join, and outer join.
26|Page
36. Give the below dataframe drop all rows having Nan.
df
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 the 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.
Code:
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
27|Page
a=[10,20,30,40,50]
df.index=a
df.loc[10]
40. What are comments and how can you add comments
inPython?
1. Single-line comment
2. Multiple-line comment
Codes needed for adding a comment
“””Note
Note
Note”””—–multiline comment
d={“a”:1,”b”:2}
28|Page
One major difference between a tuple and a dictionary is that a dictionary
is mutable while a tuple is not. Meaning the content of a dictionary can be
changed without changing its identity, but in a tuple, that’s not possible.
n1=np.array([10,20,30,40,50,60])
print(np.mean(n1))
print(np.median(n1))
print(np.std(n1))
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 point. 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.
o/p: greatlearning
29|Page
46. How do you get a list of all the keys in a dictionary?One of the
o/p: [1, 2, 3]
Syntax:
1 string_name.capitalize()
ex:
n = “greatlearning” print(n.capitalize())
o/p: Greatlearning
Syntax:
1 list_name.insert(index, element)
ex:
list = [ 0,1, 2, 3, 4, 5, 6, 7 ]
30|Page
list.insert(6, 10)
o/p: [0,1,2,3,4,5,10,6,7]
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]
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 to a for
clause, enclosed in brackets.
For ex:
list = [i for i in range(1000)]
print list
31|Page
The bytes() function returns a bytes object. It is used to convert objects
into bytes objects or create empty bytes objects of the specified size.
print(list(res))
o/p: 30,50,70,90
32|Page
_init_ methodology is a reserved method in Python aka constructor in
OOP. When an object is created from a class and _init_ methodology is
called to access the class attributes.
The two static analysis tools 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.
Not all objects can be copied in Python, but most can. We can use the “=”
operator to copy an object to a variable.
ex:
var=copy.copy(obj)
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.
33|Page
62. What is the object() function in Python?
NumPy stands for Numerical Python while SciPy stands for Scientific
Python. NumPy is the basic library for defining arrays and simple
mathematical 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 that either returns the type of the object
or returns a new type of object based on the arguments passed. ex:
a = 100
type(a)
o/p: int
34|Page
67. What is the split() function used for?
Split function is used to split a string into shorter strings using defined
separators.
letters= ('' A, B, C”)
n = text.split(“,”)
print(n)
List: A list object is an ordered collection of one or more data items that
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.
35|Page
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
tuples are immutable while List or Dictionary objects are mutable.
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:
def square(n):
return n**2
print(square.__doc__)
1 str_reverse = string[::-1]
To check the Python Version in CMD, press CMD + Space. This opens
Spotlight. Here, type “terminal” and press enter. To execute the command,
36|Page
type python –version or python -V and press enter. This will return the
python version in the next line below the command.
Code:
import pandas as pd
a=[1,2,3]
b=[2,3,5]
d={"col1":a,"col2":b}
df=pd.DataFrame(d)
df["Sum"]=df["col1"]+df["col2"]
37|Page
df["Difference"]=df["col1"]-df["col2"]
df
Output:
Data is divided into groups based on categories and then the data in
these individual groups can be aggregated by the aforementioned
functions.
df=pd.DataFrame(d)
df=df.drop(["col1"],axis=1)
df
38|Page
76. Given the following data frame drop rows having column
values as A.
Code:
d={"col1":[1,2,3],"col2":["A","B","C"]}
df=pd.DataFrame(d)
df.dropna(inplace=True)
df=df[df.col1!=1]
df
Code:
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
a=[10,20,30,40,50]
df.index=a
df
39|Page
Lambda functions are anonymous functions in Python. They are defined
using the keyword lambda. Lambda functions can take any number of
arguments, but they can only have one expression.
from functools import reduce
print(sum)
vstack() is a function to align rows vertically. All rows must have the same
number of elements.
40|Page
Code:
import numpy as np
n1=np.array([10,20,30,40,50])
n2=np.array([50,60,70,80,90])
print(np.vstack((n1,n2)))
print (str.strip())
o/p: greatlearning
41|Page
Unpickling is the reverse of pickling. The byte stream is converted back into
an object hierarchy.
To create an empty class we can use the pass command after the
definition of the class object. A pass is a statement in Python that does
nothing.
42|Page
Here is an example:
def smart_divide(func):
print("Dividing", a, "by", b)
if b == 0:
return
return func(a, b)
return inner
@smart_divide
print(a/b)
divide(1,0)
43|Page
3. In dynamically typed languages, types for variables need not be
defined before using them. Hence, it can be allocated
dynamically.
89. What is slicing in Python?
There are two variations of using the slice function. Syntax for slicing in
python:
1. slice(start,stop)
2. silica(start, stop, step) Ex:
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”, “g”)
substr1 = slice(3, 5)
print(Str1[substr1])
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”, “g”)
print(Str1[3,5])
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”, “g”)
print(Str1[substr1])
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”, “g”)
44|Page
print(Str1[0,14, 2])
Python Arrays and List both are ordered collections of elements and are
mutable, but the difference lies in working with them
Arrays store heterogeneous data when imported from the array module,
but arrays can store homogeneous data imported from the numpy
module. But lists can store heterogeneous data, and to use lists, it doesn’t
have to be imported from any module.
import array as a1
print (array1)
Or,
import numpy as a2
print(array2)
45|Page
91. What is Scope Resolution in Python?
a. Local scope – The variable declared inside a loop, the function body
is accessible only within that function or loop.
The scope resolution for any variable is made in java in a particular order,
and that order is
Local Scope -> enclosing scope -> global scope -> built-in scope
1 a for a in iterator
Or,
46|Page
1 a for a in iterator if condition
Ex:
print(list1)
print(list2)
With respect to python 2.0, the difference between range and xrange
function is as follows:
47|Page
3. range () returns a list of integers and xrange() returns a
generator object.
Example:
for i in range(1,10,2):
print(i)
.py are the source code files in python that the python interpreter
interprets.
.pyc are the compiled files that are bytecodes generated by the python
compiler, but .pyc files are only created for inbuilt modules/files.
48|Page