Preparing For Your Python Interview - The Basics - Techwers (Your Technical Interview Book 2) - KT Lindemann
Preparing For Your Python Interview - The Basics - Techwers (Your Technical Interview Book 2) - KT Lindemann
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.
>>> 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.
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.
zip(list1, list2)
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.
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.
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
# Handle error
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.
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:
Example:
isinstance(myObj, int) – returns True only when “myObj. class ” is “int”.
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.
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.
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
Both append() and extend() methods are methods of lists. These methods are
used to add the elements at the end of the list.
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:
Inside the module, you can refer to the module name as a string that is stored in
the global variable name .
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.
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.
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.
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()
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.
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