MUST Have Python Interview Questions – Part 2

By | October 8, 2017

Python Interview Questions

Continue with More Advanced Python Interview Questions and Answers

Below is the list of MUST Know Python Interview Questions with detailed answers:

Python 300x250

Explain how to make HTTP request in Python?

There are different ways to make http request:

Get Request using httplib2:

Here is an example session that uses the “GET” method:

Post Request:

Here is an example session that shows how to “POST” requests:

Back to top

Describe how to connect to MongoDB. Explain Basic CRUD operation using Python.

Install python driver for mongodb with following command:

Create a python script with name as following:

  • Insert Data with PyMongo
    There are two method to insert data to database inser_one() and insert_many() to add data to a collection. If dataset is a collection in addressbook database.


  • Find Document

    Use cursor to iterate all the address in the dataset collection of addressbook database:

    Use cursor to perform logical and operation, this will print all document those have city= london and postcode=10075.

    If we want to perform an or operation the cursor would be as following

  • Update data
    There are update_one and update_many two method  in order to update data:


  • Delete Data
    The following command will delete all the address data where city = london.

Back to top

Python Specialization from University of Michigan

How does Python handle the memory management?

The different type of memory for python are as following:Different Memory Types in Python

Memory management is very interesting in python. There are 2 types of object which are

  • Primitive object like number or string
  • Container object such as dictionary, list or user defined class

Each object has a value, one or more name and reference count. For example, in the following example.Handling Memory in Python

10 is a python object, it has 2 name x and y and the reference count for the object is 2 as two name is referred to the object.

If we execute print(id(x)), it shows the memory location for x which is also the same memory location for y. Therefore  x and y both are name for same object ‘10’.

Now if we assign x to z , we can see that the memory location for z is exactly same as x and y which is actually the memory location for 10.

If we execute, print (x is y) => it will print ‘True’, as both x and y is referring to the same object which is 300.

If we execute ‘del x’, it will not delete the object, however the reference count for 300 will be decreased by one.

If we create another object w and give it value ‘car’, it would create a string object and will get different memory location.Memory Managment in Python

If we assign w to z, which was earlier assigned with x , which was a number, z would point to the memory location of w instead of x, and x is z => false.

Heap Memory and Stack Memory:

In this above example, under main method an object 300 has been referenced with name x.  and there is another function has been defined as sqr. For the above example, the output would be:

So in both function main and sqr, the x is referencing to the same memory location. And z as well as w are referencing to the same memory location. When sqr method is returned the reference z is no longer in scope, therefore the reference count of 90000 is reduced to 0 and the returned value is assigned to w and w also referenced to 90000, the reference count to w in increased by 1. Every function is executed on stack memory and each reference is also created in stack memory. However the object is created in heap memory.Python Memory Management

Back to top

More Python Related Tutorials:

Describe the following Data Structure in Python?


This is a data structure which stores object as a (key,value) tuple.

The output would be:

Dictionary in Python


  • Dictionary is as an un-ordered set of key: value pairs where keys are unique.
  • {} is an empty dictionary.
  • The dict() constructor builds dictionaries directly from sequences of key-value pairs.
  • Indexed by keys instead of range of number; keys can be only immutable e.g number, string or tuple with number, string or tuple; if a tuple is of mutable object that can not be key of a dictionary.
  • This can be sorted.


Collections module has some subclass of its as following:

  • defaultdict: This is similar as dictionary, however, this is smarter than dictionary as if in case of any missing key in the dictionary, it creates the key and store the value for the key.
  • orderedDict: This data structure keeps all entries sorted by the order of the insertion.
    For example for a general collection as the following example:
    The output would be:Collection Output

    Another way of creating ordererdic is as following:

  • Counter: This can count the occurrence of item in a collections. For example for the following code.

    John has 2 favorite seasons, Smith has 2 favorite seasons and Barak and Ahmed each has 1 favorite seasons, therefore, the output of this program would be:Python Collections Interview Questions

  • Deque : This is a doubly linked queue. Therefpre , it is possible to add or remove items from the both end of the queue. Once interesting feature of deque is that it can be rotate, for example:

    The output would be:Python Deque Interview Questions

Back to top

What are Regular Expressions and how to use them in Python?

Regular expression is very important for data analysis and manipulation. Following table would introduce different sign used in python as well as all other programming language for regular expression.

Symbol Definition
^ matches the beginning of a string.
$ matches the end of a string.
\b matches a word boundary.
\d matches any numeric digit.
\D matches any non-numeric character.
(x|y|z) matches exactly one of xy or z.
(x) in general is a remembered group. We can get the value of what matched by using the groups() method of the object returned by
x? matches an optional x character (in other words, it matches an x zero or one times).
x* matches x zero or more times.
x+ matches x one or more times.
x{m,n} matches an x character at least m times, but not more than n times.
?: matches an expression but do not capture it. Non capturing group.
?=  matches a suffix but exclude it from capture. Positive look ahead.
a(?=b) will match the “a” in “ab”, but not the “a” in “ac”
In other words, a(?=b) matches the “a” which is followed by the string ‘b’, without consuming what follows the a.
?! matches if suffix is absent. Negative look ahead.
a(?!b) will match the “a” in “ac”, but not the “a” in “ab”.
Regular expression flag:
Flag Description
re.I Ignore case.
re.L Matches pattern according to locale.
re.M Enable multi line regular expression.
re.S Make the “.” special character match any character at all, including a newline.
re.U Matches pattern according to Unicode character set.
re.X Ignore whitespace and treats unescaped # as a comment marker.

Example: Validate Email Address

The output would be:Python Regular Expression Questions

Back to top

Python Certification Training

Give some example of Functional programming in Python?

Here is an example of traditional square function in python:

Now in functional programming a function take and input and generate output without any intermediate step. If we rewrite the above function as following:

In python map, filter, reduce, lambda are used for functional programming. To Learn Python, 3 best courses on udemy are here.

Back to top

Describe Python’s Exception Handling mechanism in brief?

Exception Name
Exception Parent class of all exception.
StopIteration If iterator has no next object to iterate.
SystemExit If system exit abruptly.
StandardError Parent class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError When there is an error in numeric calculation.
OverflowError Raised when a result of any numerical computation is too large.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError When there is a divition by 0 or module by 0 occur.Python Exception Interview Questions
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
ImportError When the module  to be imported is not installed.Python Exception Questions
KeyboardInterrupt Ctrl+C caused this interruption exception.
LookupError Base or parent class for all lookup errors.
IndexError Similar to ArrayIndexOutOfExcerption in Java.
KeyError Dictionary is a container of list of (key,value) air. If the key is not found, this exception is raised.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it.
EnvironmentError Base class for all exceptions which are outside the Python environment.
IOError Raised when there is a file red/write error. Also raised for operating system-related errors.
SyntaxError Raised for any error in Python syntax.
IndentationError Indention is very important in python for each codde block. This error is raised when indentation is not correct.
SystemError If Python interpreter finds an exception. This can be handled in code as the interpreter does not exit.
TypeError Raised when any operation is intended to be executed on a wrong data type.
ValueError Raised when type conversation can not occur due to wrong value.
RuntimeError Raised when an unknown exception occur.
NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

Try-except-finally Block:

Nested Try-except Block:

Try Block without Except:

Each try block must be followed by either a except of finally block.

Different Ways to Handle Exception in Python:

  • Catch exception argument: Exception or can be handled with argument. As in following exception, ‘car’ can not be converted to int and args of error object define the reason for exception.Catch Exception Argument Question
  • Multiple exception in same line.

Throw Exception:

Raise command is used to throw an exception either user defined or built-in as following:

  • If the error type is not known, it is possible to catch all kind of exception.Throw Exception Interview Question
  • It is also possible to detect which kind of error has been raised.Detect Error Type
  • It is also possible to pass user defined argument for the thrown exception.User Defined Argument

Back to top

How Object Serialization works in Python?

Object serialization is a simple way to convert an object from format to others and at the same way later this converted form of object can be converted back to the earlier version of object. Python uses a particular mechanism in order to serialize object which is known as ‘pickling’. Using pickling an object can be converted to a binary object.

There are two steps in order to serialize an object:

  • Import the pickling module.
  • Call the dump method with the object as an argument.

Here john and smith are two different type of object. Picling has been used to convert john to smith.

Similarly, way it is also possible to de-serialize the object:

If we only want to convert any python object to json , there are the following two steps need to be executed:

  • Import JSON module.
  • Call dumps function from JSON module and pass the object as an argument.

Here, the python object has been serialized to a json variable , the output would be as following:Object Serialization Question in Python

Back to top

Describe Object Oriented feature in Python?

There are two main concept of object oriented programming language. Python also support them.

  • Inheritance
  • Polymorphism


Any class can be extended from another class. And the child class can access the method of the parent class.Inheritance Question in Python

Following are some example of method access across parent class and child class.

The output would be as following:Inheritance in Python


In this following class diagram, both Window and Wall are of Structure type. Therefore, for both of them Structure is the parent class.Polymorphism in Python

So now if we run the following example:Python Structure Questions

The output would be as following:Python Structure Output

As the destroy method has not been implemented in the child classed in Window or Wall therefore, there is an exception has been thrown.  Now if the program is fixed and all the abstract methods are implemented as following the output would be:

Advanced Python Interview Questions

Back to top

The course is designed to cover web, database, data science, web scrapping, image processing, web visualization and much more.

Followings are few highlight about this Python Online Course:

  • Best Seller Udemy Online Course
  • 40,016++ students enrolled
  • 6,251 Review available
  • 23 Hours on-demand videos
  • 28 Articles
  • 36 Supplemental Resource
  • Access on Mobile and TV
  • Certificate of Completion
  • Lifetime Access
  • 30 days Money back guarantee
  • You can get the course at Discounted Price here.

Most attractive feature is 30 days Money Back Guarantee means there is NO RISK. If you didn’t like this Python Online Course, you can refund your money back within 30 days of purchase.


We will soon add a small Online Test to enhance user skills. Keep in touch.
Step forward in 2017: Build in-demand career skills with Coursera

More Python and Related: