You are on page 1of 83

Preparing for Your Python Interview

The Basic s: Te c hnic al Que stio ns and Answe rs

By K.T. Lindemann
Introduction
The Python Interpreter
The Basics of Python
Python Strings, Sequences, and Lists
File Handling in Python
Basics of Python Modules
Compare and Contrast
Common Python Tools and Frameworks
Common Python Technical Problems
Introduction
Python is an interpreted, high-level programming language for general-purpose
programming. First introduced in 1991, it has grown to consistently place in
the top ten of most used programming languages. Its slimmed down syntax and
use of whitespace versus formal notation made it a popular language of choice
for industries that valued speed of development.

When interviewing for a Python developer position, where do you start your
study? Python is used in a diverse array of applications, including web
development, scientific computing, and 3D animation. Many specialized
frameworks and modules exist for every field. A biologist may never know
about Django while a web developer may never run into numpy.

This book aims to cover the basics of a Python interview. We'll touch on a few
prominent modules, but for the most part, the questions in this book will focus
on core python concepts that every developer should know. You will find clear
and concise answers that will help you learn how to explain important
concepts and ideas in Python, as well as detailed answers to a few common
technical coding problems.

Good luck!
The Python Interpreter
Question: Which command do you use to exit help window
or help command prompt?
quit

When you type quit at the help’s command prompt, the python shell prompt will
appear by closing the help window automatically.
Question: Explain how Python does Compile-time and
Run-time code checking?
Python performs some amount of compile-time checking, but most of the checks
occur during code execution. Consequently, if the Python code references a
user-defined function that does not exist, the code will compile successfully. In
fact, the code will fail with an exception only when the code execution path
references the function which does not exists.
Question: Differentiate between .py and .pyc files?
Both .py and .pyc files holds the byte code. “.pyc” is a compiled version of
Python file. This file is automatically generated by Python to improve
performance. The .pyc file has byte code which is platform independent and
can be executed on any operating system that supports the .pyc format.
The Basics of Python
Question: What is PEP 8?
PEP 8 is a coding convention intended to make your Python standardized and
more readable.
Question: What is a "docstring" in Python?
A Python documentation string is known as docstring, it is a way of
documenting Python functions, modules and classes.
Question: How memory is managed in Python?
Python memory is managed by the Python private heap space. All Python
objects and data structures are located in a private heap. The programmer does
not have an access to this private heap. Instead, the interpreter takes care of
this Python private heap.

The allocation of Python heap space for Python objects is done by the Python
memory manager, which can be accessed by the core API.

Python also has an inbuilt garbage collector which recycles and frees all the
unused memory, making it available to the heap space.
Question: What is the difference between list and tuple?
The difference between lists and tuples is that lists are mutable while tuples
are not.
Question: How do you convert a number to a string in
Python?
A number can be converted to a string using the function str(). If you want the
octal or hexadecimal representation of a number, you can use the function oct()
or hex().
Question: Describe the use of namespaces in Python?
In Python, each package, module, class, function and method function owns a
"namespace" in which variable names are resolved. There is also a global
namespace that's used if the name isn't in the local namespace.

Each variable name is first checked in the local namespace, then checked in the
global namespace.
Question: What is a negative index in Python?
Python sequences can be indexed by both positive and negative numbers. For
positive indexing, 0 is the first index, 1 is the second index and so forth. For
negative indexing, (-1) is the last index and (-2) is the second last index and so
forth.
Question: What is lambda in Python?
It is a single expression anonymous function often used as an inline function.
Question: What is pickling and how does it differ from
unpickling?
Pickling is a process by which a Python object get converted into a string via a
pickle module. The process then puts it into a file by calling the dump()
method.

Unpickling does the reverse of the above process. It retrieves the stored string
and turns it back into an object.
Question: What is the “pass” keyword used for in Python?
The “pass” keyword is a no-operation statement in Python. It signals that no
action is required. It works as a placeholder in compound statements which are
intentionally left blank.
Question: Does Python allow arguments pass by value or
pass by reference?
Python is neither "call-by-reference" nor "call-by-value". In Python a variable
is not an alias for a location in memory. Rather, it is simply a binding to a
Python object. So it is more accurate to say that Python is “pass-by-object-
reference”.
Question: What are the different methods Python provides
for copying an object?
We can either use a “Shallow Copy” or follow a “Deep Copy” approach.

Shallow Copy Method.


The content of an object (say dictionary) doesn’t get copied by value but by
creating a new reference.

>>> a = {1: [1,2,3]}


>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})

Deep Copy Method.


It copies all the contents by value.

>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
Question: How many kinds of sequences are supported by
Python? What are they?
Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray,
xrange, and buffer.

Note that xrange is deprecated in python 3.5.X.


Question: How do you set a global variable inside a
function?
You can use a global variable in other functions by declaring it as global in
each function that assigns to it:

globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print globvar \
set_globvar_to_one()
print_globvar() # Prints 1
Question: How do you share global variables across
modules?
If you add a variable to the <__builtin__> module, it will be accessible as if it
were a global from any other module that includes <__builtin__> , which is all
of them, by default.
Question: Explain Python's zip() function?
The zip() function takes multiple lists and transform them into a single list of
tuples by taking the corresponding elements of each of the lists that are passed
as parameters.

list1 = ['A','B','C'] and list2 = [10,20,30].

zip(list1, list2)

Results in a list of tuples: [('A',10),('B',20),('C',30)]


When the given lists are of different lengths, zip stops generating tuples when
the first list ends.
Question: Explain the characteristics of Python's Objects.
Python’s Objects are instances of classes and are created at the time of
instantiation.

One or more variables can reference the same object in Python.

Each object has a unique id which can be obtained by using id() method.

Each object can be either mutable or immutable based on the type of data they
hold.

Whenever an object is not being used in the code, it gets destroyed


automatically garbage collected or destroyed
Question: Explain how to overload constructors or methods
in Python.
Python’s constructor – _init__ () is a first method of a class. Whenever we try
to instantiate an object __init__() is automatically invoked by python to
initialize the members of that object.
Question: How do you create a dictionary which can
preserve the order of pairs?
Regular Python dictionaries iterate over <key, value> pairs in an arbitrary
order, hence they do not preserve the insertion order of the <key, value> pairs.

Python 2.7. introduced a new “OrderDict” class in the “collections” module


and it provides the same interface like the general dictionaries but it traverses
through keys and values in an ordered manner depending on when a key was
first inserted.

from collections import OrderedDict


d = OrderDict([('Company-id':1),('Company-Name':'Intellipaat')])
d.items() # displays the output as: [('Company-id':1),('Company-Name':'Intellipaat')]
Question: When should a dictionary be used instead of a
list?
Dictionaries are best suited when the data is labelled, i.e., the data is
composed of key-value pairs.

Lists are a better option for storing collections of unlabeled items.


Question: What is JSON? How would convert JSON data
into Python data?
JSON stands for JavaScript Object Notation. It is a popular data format for
storing and transferring data.

Generally JSON is built on 2 structures.


1. A collection of <name, value> pairs.
2. An ordered list of values.

As Python supports JSON parsers, JSON-based data is actually represented as


a dictionary in Python. You can convert JSON data into python using the load()
function of the json module.
Question: What is a Class? How do you create it in Python?
A class is a blue print/ template of code /collection of objects that has same set
of attributes and behavior. To create a class, use the keyword class followed
by class name beginning with an uppercase letter.

For example, a person belongs to class called Person class. A Person class can
be defined as:

class Person():

def inputName(self,fname,lname):
self.fname=fname self.lastname=lastname
Question: How do you handle exceptions in Python?
Exception handling prevents code and scripts from breaking on receipt of an
error at runtime.

The simplest way to handle exceptions is with a "try-except" block:

(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
# Handle error

try: it will try to execute the code


except: catches all errors or can catch a specific error.
finally: it is an optional clause and will execute regardless of the try/catch
statements
Question: What is multithreading? Give an example.
Threading in python is used to run multiple threads (tasks, function calls) at the
same time.

Multiple threads within a process share the same data space with the main
thread and can therefore share information or communicate with each other
more easily than if they were separate processes.

Threads are sometimes called light-weight processes. They do not require


much memory overhead and are "cheaper" to run than processes.
Question: How instance variables are different from class
variables?
Instance variables are local to that object. Two objects of the same class
maintain distinct values for their variables.

Class variables belong to the class. All the objects of the same class will share
the same value for a given class variable.
Question: Which methods of Python are used to determine
the type of instance and inheritance?
Python has 2 built-in functions that work with inheritance:

isinstance(): this method checks the type of instance.

Example:
isinstance(myObj, int) – returns True only when “myObj. class ” is “int”.

issubclass(): this method checks class inheritance

Example:
issubclass(bool, int) – returns True because “bool” is a subclass of “int”.
issubclass(unicode, str) – returns False because “unicode” is not a subclass of
“str”.
Question: How to retrieve data from a table in MySQL
database through Python code? Explain.
1. import MySQLdb module as : import MySQLdb
2. establish a connection to the database.
db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-
name”, “password”=”password”, “database-name”=”database”)
3. initialize the cursor variable upon the established connection: c1 =
db.cursor()
4. retrieve the information by defining a required query string. s = “Select
* from table1”
5. fetch the data using fetch() methods and print it. data = c1.fetch(s)
6. close the database connection. db.close()
Python Strings, Sequences, and Lists
Question: How do you convert a string to a number in
Python?
Python provides the <int()> method, a standard built-in function to convert a
string into an integer value.

You can call it with a string containing a number as the argument, and it returns
the number converted to an actual integer.
Question: What is slicing in python?
Slicing in Python is a mechanism to select a range of items from Sequence
types like strings, list, and tuples.

a[start:end] # returns items start through end-1


a[start:] # returns items start through the rest of the array
a[:end] # returns items from the beginning through end-1
a[:] # returns a copy of the whole array

The other feature is that start or end may be a negative number, which means it
counts from the end of the array instead of the beginning.

a[-1] # last item in the array


a[-2:] # last two items in the array
a[:-2] # everything except the last two items
Question: Describe how enumerate() is used in Python?
Using the enumerate() function, you can iterate through the sequence and
retrieve the index position and its corresponding value at the same time.

>>> for i,v in enumerate([‘Python’,’Java’,’C++’]):


print(i,v)
0 Python
1 Java
2 C++
Question: What are iterators in Python?
Iterators in Python enables to traverse containers like a list or a set of
elements. For a container to support iterator, it must provide
the <__iter__()> method.
Question: What are generators in Python?
Generators are a way of implementing iterators. A generator function is a
normal function except that it contains yield expression in the function
definition making it a generator function.

This function returns a generator iterator known as a generator.

To get the next value from a generator, we use the same built-in function as for
iterators: <next()>. <next()> takes care of calling the
generator’s <__next__()> method.
Question: How do you perform pattern matching in
Python? Explain
Regular Expressions/REs/regexes enable us to specify expressions that can
match specific “parts” of a given string.

Python’s “re” module provides regular expression patterns and was introduce
from later versions of Python 2.5. “re” module is providing methods for search
text strings, or replacing text strings along with methods for splitting text
strings based on the pattern defined.
Question: What are some methods for matching and
searching the occurrences of a pattern in a given String ?
There are 4 different methods in “re” module to perform pattern matching.
They are:
match() matches the pattern only to the beginning of the String
search() scan the string and look for a location the pattern matches
finditer() finds all the occurrences of match and return them as an iterator
finds all the occurrences of match and return them as a list– finds
findall()
all the occurrences of match and return them as an iterator

48. Differentiate between append() and extend() methods. ?

Both append() and extend() methods are methods of lists. These methods are
used to add the elements at the end of the list.

append(element) – adds the given element at the end of the list.


extend(another-list) – adds the elements of another list at the end of this list.
File Handling in Python
Question: What modules do you need to handle files in
Python?
Basic file handling in Python requires no importing of modules.
Question: What functions are used to read files in Python?
There are three read functions: read(),readline() and readlines()

#return one big string


read()

#return one line at a time


readline()

#returns a list of lines


readlines()
Question: What functions are used to write files in Python?
There are two write methods to write a sequence of strings to the file.

#Used to write a fixed sequence of characters to a file


write()
#writelines can write a list of strings.
writelines()
Question: Explain the use of with statement?
In python, the “with” statement is used to open a file, process the data present
in the file, and also to close the file without calling a close() method. The
“with” statement makes the exception handling simpler by providing cleanup
activities.

General form of with:


with open(“file name”, “mode”) as fileVariable:
# processing statements
Question: Why should you close a file after opening it?
When you’re done with a file, use close() to close it and free up any system
resources taken up by the open file.
Question: Explain all the file processing modes supported
by Python?
Python allows you to open files in several modes.

They are:
read-only mode, write-only mode, read-write mode, and append mode by
specifying the flags “r”, “w”, “rw”, “a” respectively.

A text file can be opened in any one of the above said modes by specifying the
option “t” along with “r”, “w”, “rw”, and “a”, so that the preceding modes
become “rt”, “wt”, “rwt”, and “at”.

A binary file can be opened in any one of the above said modes by specifying
the option “b” along with “r”, “w”, “rw”, and “a” so that the preceding modes
become “rb”, “wb”, “rwb”, “ab”.
Question: Explain how to redirect the output of a python
script from standout on to a file?
They are two possible ways of redirecting the output from standout to a file.
1. Open an output file in “write” mode and the print the contents into that
file using the sys.stdout attribute.

import sys
filename = “outputfile” sys.stdout = open() print “testing”

2. On the command line, you can redirect the output of a python script to a
file. For example:

redirect_output.py has the following code:


print “Testing”

execution: python redirect_output.py > outputfile


Question: How do you check the file existence and their
types in Python?
This method is used to check for the existence of a file. It
os.path.exists()
returns True if the file exists, false otherwise
This method is used to check whether the give path
os.path.isfile() references a file or not. It returns True if the path
references to a file, else it returns false.
This method is used to check whether the give path
os.path.isdir() references a directory or not. It returns True if the path
references to a directory, else it returns false.
os.path.getsize() Returns the size of the given file
os.path.getmtime() Returns the timestamp of the given path.
Basics of Python Modules
Question: What is a Python module?
A module is a Python script that generally contains import statements,
functions, classes and variable definitions, and Python runnable code. it
“lives” in a file with a ‘.py’ extension. zip files and DLL files can also be
modules.

Inside the module, you can refer to the module name as a string that is stored in
the global variable name .

A module can be imported by other modules in one of the two ways:


import
from module-name import
Question: What are the core default modules available in
Python?
Following are a few of the default modules available in Python.
email – Help to parse, handle, and generate email messages.
string – Contains functions to process standard Python strings.
sqlite3 – Provides methods to work with the SQLite database.
XML – Enables XML support.
logging – Adds support for log classes and methods.
traceback – Allows to extract and print stack trace details.
Question: How can you create a Python module?
Writing Python modules is very simple. To create a module of your own,
simply create a new .py file with the module name, and then import it using the
Python file name (without the .py extension) using the import command.
Question: What are Python packages?
Packages are namespaces which contain multiple packages and modules.
Question: Why is <__init__.Py> module used in Python?
The <__init__.py> module can help fulfill the following objectives.
1. It makes Python interpret directories as containing packages by excluding the
ones with a common name such as string.
2. It grants a programmer the ability to decide whether or not a package is a
directory.
3. However, the <__init__.py> can also be an empty file. It can then help in
executing the initialization code for a package or setting
the <__all__> variable.
Question: What are some common Python modules for
Statistical, Numerical and scientific computations ?
numPy This module provides an array/matrix type and is useful for
doing computations on arrays.
scipy This module provides methods for doing numeric integrals
and solving differential equations.
pylab This is a module for generating and saving plots.
matplotlib This is a module used for managing data and generating
plots
Compare and Contrast
Question: How are the functions help() and dir() different?
These are the two functions that are accessible from the Python Interpreter.
These two functions are used for viewing a consolidated dump of built-in
functions.

Help() will display the documentation string. It is used to see the help related
to modules, keywords, and attributes, among other things. If no argument is
given, the help system starts on the interpreter console. If the argument is a
string, then the string is looked up as the name of a module, function, class,
method, keyword, or documentation topic, and a help page is printed on the
console. If the argument is any other kind of object, a help page on the object is
generated.

Dir() is similar to help but will not necessarily return the same results. Without
arguments, it will return the list of names in the current local scope. With an
argument, it attempts to return a list of valid attributes for that object. When
used on an object, dir() attempts to produce the most relevant information for
that object. It will not necessarily return a complete listing of information for
the object.
Question: What are the differences between split(), sub()
and subn() methods:?
Spit(), sub() and subn() are three functions used to find parts of a string.

split() Uses a regex pattern to “split” a given string into a list.


Finds all substrings where the regex pattern matches and then
sub()
replaces them with a different string
Finds all substrings where the regex pattern matches and then
subn() returns the new string along with the number of replacements.
Common Python Tools and Frameworks
Although the focus of this book is vanilla python, we will touch upon a few
common tools and frameworks that might come up in a basic python interview.
Question: Is there a tool for finding bugs or performing
static analysis?
PyChecker is a static analysis tool. It finds problems that are typically caught
by a compiler for less dynamic languages, like C and C++.

Types of problems that can be found include:


No global found (e.g., using a module without importing it)
Passing the wrong number of parameters to
functions/methods/constructors
Passing the wrong number of parameters to builtin functions & methods
Using format strings that don't match arguments
Using class methods and attributes that don't exist
Changing signature when overriding a method
Redefining a function/class/method in the same scope
Using a variable before setting it
self is not the first parameter defined for a method
Unused globals and locals (module or variable)
Unused function/method arguments (can ignore self)
No doc strings in modules, classes, functions, and methods

Pylint is a source code, bug and quality checker for Python. It follows the style
recommended by PEP 8, the Python style guide. It is often used automatically
as part of continuous integration.
Question: How is Unit Testing performed in Python?
Python packages a unit testing framework called <Unittest>. It supports:
Automation testing.
Sharing of setup and shutdown code for tests.
Aggregation of tests into collections.
Independence of the tests from the reporting framework.
Question: What is Flask?
Flask is a Python web framework on the Werkzeug WSGI toolkit and Jinja2
template engine.

it does not require particular tools or libraries. It has no database abstraction


layer, form validation, or any other components where pre-existing third-party
libraries provide common functions. However, Flask supports extensions that
can add application features as if they were implemented in Flask itself.
Question: What are the differences between Django,
Pyramid, and Flask?
Flask is a "microframework" primarily aimed at small applications with
simpler requirements.

Pyramid and Django are both aimed at larger applications, but take different
approaches to extensibility and flexibility. Pyramid targets flexibility and lets
the developer use the right tools for their project. This means the developer
can choose the database, URL structure, templating style, and more. Django
aims to include all the pieces a web application will need.

Django includes an ORM out of the box, while Pyramid and Flask leave it to
the developer to choose how (or if) they want their data stored.
Common Python Technical Problems
Question: Print the sum of numbers starting from 1 To 100
(Inclusive)?
# note that range does not include the last number
print sum(range(1,101))
Question: Remove the duplicate elements from the given
list?
words = [‘one’, ‘one’, ‘two’, ‘three’, ‘three’, ‘two’]

A simple solution is to iterate over the list, identify duplicates and remove
them.

a = [1,2,2,3]
list(set(a))
Question: What is the best approach for storing a list of first
and last names?
A list of first and last names is best stored as a list of dictionaries. The
following format can be used.

[{ ‘first_name’: ‘John’, ‘last_name’: ‘Smith’},


{‘first_name’: ‘Jane’, ‘last_name’: ‘Doe’}]
Write a Python program to read an entire text file.
def file_read(fname):
txt = open(fname)
print(txt.read())

file_read('test.txt')
Question: How would you display the contents of text file
in reverse order?
1. Convert the given file into a list.
2. Reverse the list by using reversed()

for line in reversed(list(open(“file-name”,”r”))):


print(line)
Question: Write a python program to find the longest words
in a file.
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]

print(longest_word('test.txt'))
Question: Write a program which will find all such numbers
which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included). The numbers
obtained should be printed in a comma-separated sequence
on a single line.
l=[]
for i in range(2000, 3201):
if (i%7==0) and (i%5!=0):
l.append(str(i))

print ','.join(l)
Question: Write a program which can compute the factorial
of a given numbers.
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
Question: Given an integer n, write a program to generate a
dictionary that contains (i, i*i) where i is an integer
between 1 and n (both included)
Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

d=dict()
for i in range(1,n+1):
d[i]=i*i

print d
Question: Write a program which accepts a sequence of
comma-separated numbers from the console and generate
a list and a tuple which contains every number.

For example, if the following input is supplied to the


program:
18,67,55,33,12,98
Then, the output should be:
['18', '64', '14', '87', '12', '91']
('18', '64', '14', '87', '12', '91')

values=raw_input()
l=values.split(",")
t=tuple(l)
print l
print t
Question: Write a program which accepts a sequence of
comma separated 4 digit binary numbers as its input and
then check whether they are divisible by 5 or not. The
numbers that are divisible by 5 are to be printed in a
comma separated sequence.
value = []
items=[x for x in raw_input().split(',')]
for p in items:
intp = int(p, 2)
if not intp%5:
value.append(p)

print ','.join(value)
Question: Use a list comprehension to square each odd
number in a list.
def square_it(values):
numbers = [x for x in values.split(",") if int(x)%2!=0]
print ",".join(numbers)
Question 6: What does this code output?
def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)

f(2)
f(3,[3,2,1])
f(3)

Output:
[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]
Question: Write a method which can calculate square value
of number.
def square(num):
return num ** 2

You might also like