Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python Interview Questions & Answers

1. Given a list and a number find two numbers in the list that sums up to the number given?

a = [1,2,3,4,5,6,8] given_no = 9
mm = [] count =0
for x,y in enumerate(a):
for j in range(x+1, len(a)):
total_of_two_items = a[x] + a[j] if total_of_two_items == given_no:
mm.append((a[x],a[j]))
print mm

2. Which is the shortest way to read a file?

Two memory efficient ways in ranked order (first
is best) –

1. use of with – supported from Python 2.5 and above
2. use of yield if you really want to have control over how much to read

1.USE OF WITH

with is the nice and efficient pythonic way to read large files.

advantages –

1) file Object is automatically closed after exiting from with execution block.
2) exception handling inside the with block. 3) memory for loop iterates through the f file object line by line. internally it does buffered IO (to optimized on costly IO operations) and memory management. with open(“x.txt”) as f:
for line in f:
do something with data
The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered IO and memory management so you don’t have to worry about large files.

2. USE OF YIELD
Sometimes one might want more fine-grained control over how much to read in each iteration. In that case use iter & yield. Note with this method one explicitly needs close the file at the end.
def readInChunks(fileObj, chunkSize=2048):
“””
Lazy function to read a file piece by piece.
Default chunk size: 2kB.
“””
while True:
data = fileObj.read(chunkSize)
if not data:
break
yield data

f = open(‘bigFile’)
for chuck in readInChunks(f):
do_something(chunk)
f.close()

3. Why is <__init__.py> module used in Python?

The <__init__.py> module can help in fulfilling 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 with the control to decide which directory is a package and which is not.

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.

4. 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.

SHALLOW COPY METHOD.
>>> 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]})
1
2
3
4
5
6
7
>>> 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]})
1
2
3
4
5
6
>>> 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]})

5. How will 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 # No need for global
declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
1
2
3
4
5
6
7
8
I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that’s what you’re playing with by explicitly requiring the global keyword.

6. forelse in python

Python has an interesting for statement which lets you specify an else suite.

In a construct like this one:

for i in foo:
if bar(i):
break
else:
baz()
the else suite is executed after the for, but only if the for terminates normally (not by a break).
Here’s some code written without for…else:
def contains_even_number(l):
“Prints whether or not the list l contains an even number.”
has_even_number = False
for elt in l:
if elt % 2 == 0:
has_even_number = True
break
if has_even_number:
print “list contains an even number”
else:
print “list does not contain an even number”
The equivalent code snippet below illustrates how the use of for…else lets you remove an extraneous flag variable from that loop:
def contains_even_number(l):
“Prints whether or not the list l contains an even number.”
for elt in l:
if elt % 2 == 0:
print “list contains an even number”
break
else:
print “list does not contain an even number”
Use your good judgment when deciding whether to use the for…else construct.

It’s not unequivocally better, but when there’s an asymmetry between the two possibilities, you can make your code more readable by using for…else to keep the “happy path” logic at the top and the exceptional/error case at the bottom.

7. How to make class iterable

Iterator objects in python conform to the iterator protocol, which basically means they provide two methods:
__iter__() and next().

The __iter__ returns the iterator object and is implicitly called at the start of loops.

The next() method returns the next value and is implicitly called at each loop increment.
next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.

Here’s a simple example of a counter:

class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self

def next(self): # Python 3: def
__next__(self)
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current – 1

for c in Counter(3, 8):
print c
This will print:
3
4
5
6
7
8

8. Conditional Import in Python

You could except the ImportError exception:
try:
from Pyside2 import QtCore, QtGui
except ImportError:
from PySide import QtCore, QtGui

Alternatively, you can use the importlib module:

import importlib
import sys
PySide = importlib.import_module(‘Pyside2’ if
‘Pyside2’ in sys.modules else ‘PySide’)

9. Write a class which will count the number

object created of that class.USING STATIC METHOD.

class Base:
numOfInstances = 0
def __init__(self):
Base.numOfInstances += 1
def getNumInstances():
print Base.numOfInstances
# Using python built-in staticmethod,
@decoration symbol also can be used

getNumInstances = staticmethod(getNumInstances)
b1 = Base()
b1.getNumInstances()
# It should print 1
b2 = Base()
b2.numOfInstances = 15
b1.getNumInstances()
# It should print 2
b2.getNumInstances()
#It should print 2
Lets extend Base class and see what happens –
class Base:
numOfInstances = 0
def __init__(self):
Base.numOfInstances += 1
def getNumInstances():
print Base.numOfInstances
# Using python built-in staticmethod,@decoration symbol also can be used

getNumInstances =staticmethod(getNumInstances)
class Derived(Base):
numOfInstances = 0
def __init__(self):
Derived.numOfInstances +=1
b1 = Base()
d1 = Derived()
d2 = Derived()
d1.getNumInstances()
#It’s printing 1 But we have created 2 instances of Derived
Derived.getNumInstances()
#It’s printing 1 But we have created 2 instances of Derived
We shouldn’t use static method –

1.If we have to act on data which may differ among instances of a class. (Instance Method should be used in such scenario)
2. If we have to act on data which may differ for class objects in a class hierarchy. (Class Method should be used in such scenario)

You might want to know then where should we use static method ?
It’s safe to use static method if it’s not acting on any data or a method which can be used by all the instances and all the classes in hierarchy. Static Method is best suited if Base class needs to keep count of instances of all it’s subclass too.

class Base:
numOfInstances = 0
def __init__(self):
Base.numOfInstances += 1
def getNumInstances():
print Base.numOfInstances
getNumInstances =
staticmethod(getNumInstances)
class Derived(Base):
def __init__(self):
Base.__init__(self)

b1 = Base()
d1 = Derived()
d2 = Derived()
d1.getNumInstances()
#It should print 3
Base.getNumInstances()
#It should print 3

10. Write a class which will count the number object created of that class.USING CLASS METHOD:

class Base:
numOfInstances = 0
def countInstances(cls):
cls.numOfInstances += 1
countInstances = classmethod(countInstances)
def getNumInstances(cls):
print cls.numOfInstances
getNumInstances = classmethod(getNumInstances)
def __init__(self):
self.countInstances()
class Derived(Base):
numOfInstances = 0
def __init__(self):
Base.__init__()
# Why we call explicitly to super class’s
__init__ ??
#people from c++ background who already know oops, We will talk about operator overloading in another article
b1 = Base()
b2 = Base()
d1 = Derived()
d2 = Derived()
d3 = Derived()
b1.getNumInstances()
Base.getNumInstances()
#Both should print 2
d1.getNumInstances()
Derived.getNumInstances()
#Both should print 3

11. Difference between read and readline

Both are used to read the content from the file but in different ways.
f.read() reads the whole file as an individual string and allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution.
If file xyz.py contains text
“`def print_triangle(n):
for x in range(1, n + 1):
num_list = [str(num % 10) for num in range(x, 2*x)]“`
If i write below code with open(‘xyz.py’, ‘r’) as f:
print f.read()
The o/p will be whole file
>>> def print_triangle(n):
for x in range(1, n + 1):
num_list = [str(num % 10) for num in range(x, 2*x)] f.readline() reads a single line of the file, allowing the user to parse a single line without reading the entire file.
If i use only readline()
with open(‘xyz.py’, ‘r’) as f:
print f.readline()
The o/p will be whole file

>>> def print_triangle(n):

12. Explain different ways to trigger or raise exceptions in your python script ?

You can trigger an exception in your Python script in following ways.
1. raise – it is used to manually raise an exception:
raise exception-name (“message”)
Eg: >>> voting_age = 15
>>> if voting_age O/p: ValueError: voting age should be atleast 18 and above

2. assert statement assert statements are used to tell your program to test that condition attached to assert keyword, and trigger an exception whenever the condition becomes false.

Eg: >>> a = -10
>>> assert a > 0 #to raise an exception whenever a is a negative number
O/p: AssertionError
Another way of raising and exception can be done by making a programming mistake, but that’s not usually a good way of triggering an exception.

13. How is Inheritance and Overriding methods are related?

If class A is a subclass of class B, then everything in B is accessible in /by class A. In addition, class A can define methods that are unavailable in B, and also it is able to override methods in B. For Instance, If class B and class A both contain a method called func(), then func() in class B can override func() in class A. Similarly, a method of class A can call another method defined in A that can invoke a method of B that overrides it.

14. What are the different methods Python provides for copying an object?

We can either use a “Shallow Copy” or follow a “Deep Copy” .
Shallow Copy method.
The content of an object (say dictionary)doesn’t get copied by value but by creating a new reference.
SHALLOW COPY METHOD.
>>> 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]})
1
2
3
4
5
6
7
>>> 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]})

1
2
3
4
5
6
>>> 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]})

15. Does Python supports interfaces like in Java? Discuss.

Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature are provided by the Python’s “abc” module. Abstract Base Class is a mechanism for specifying what methods must be implemented by its implementation subclasses. The use of ABC’ provides a sort of “understanding” about methods and their expected behaviour. This module
was made available from Python 2.7 version onwards.

16. forelse in python

Python has a for syntax which can be combined with else syntax.
for i in foo:
if bar(i):
break
else:
baz()
the else suite is executed after the for, but only if the for terminates normally.
Here’s code written without for…else:
def contains_even_number(l):
“Prints whether or not the list l
contains an even number.”
has_even_number = False
for elt in l:
if elt % 2 == 0:
has_even_number = True
break
if has_even_number:
print “list contains an even number”
else:
print “list does not contain an even
number”
The equivalent code snippet below illustrates how the use of for…else lets you remove flag variable from that loop:
def contains_even_number(l):
“Prints whether or not the list l
contains an even number.”
for elt in l:
if elt % 2 == 0:
print “list contains an even number”
break
else:
print “list does not contain an even number”
Use your good judgment when deciding whether to use the for…else construct.When there’s an asymmetry between the two possibilities, you can make the code more readable by using for…else to keep the exceptional/error case at the bottom.

17. What are Accessors, mutators, @property?

Accessors and mutators are called getters and setters in language like “Java”. For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX(). Python has @property “decorator” that allows you to add getters and setters to access the attribute of the class.

18. In the case of Multiple inheritance, if a child class C is derived from two base classes say A and B as: class C(A, B):

which parent class method will be invoked by the interpreter whenever object of class C calls a method func() that is existing in both the parent classes say A and B and does not exist in class C as “c1.func()”?

since class C does not contain the definition of the method func(), they Python searches for the func() in parent classes. As the search is performed in a left-to-right fashion, Python executes the method func() which is  present in class A and not the func() method in B.

19. Write a class which will count the number object created of that class.USING STATIC METHOD.

class Base:
numOfInstances = 0
def __init__(self):
Base.numOfInstances += 1
def getNumInstances():
print Base.numOfInstances
# Using python built-in staticmethod,@decoration symbol also can be used
getNumInstances = staticmethod(getNumInstances)

b1 = Base()
b1.getNumInstances()
# It should print 1
b2 = Base()
b2.numOfInstances = 15
b1.getNumInstances()
# It should print 2
b2.getNumInstances()
#It should print 2
Lets extend Base class and see what happens –
class Base:
numOfInstances = 0
def __init__(self):
Base.numOfInstances += 1
def getNumInstances():
print Base.numOfInstances
# Using python built-in staticmethod, @decoration symbol also can be used
getNumInstances = staticmethod(getNumInstances)

class Derived(Base):
numOfInstances = 0
def __init__(self):
Derived.numOfInstances +=1
b1 = Base()
d1 = Derived()
d2 = Derived()
d1.getNumInstances()
#It’s printing 1 But we have created 2 instances of Derived
Derived.getNumInstances()
#It’s printing 1 But we have created 2 instances of Derived
We shouldn’t use static method –
1.If we have to act on data which may differ among instances of a class. (Instance Method should be used in such scenario)
2. If we have to act on data which may differ for class objects in a class hierarchy. (Class Method should be used in such scenario)
You can use static method if it is not acting on any data or a method which can be used by all the instances and all the classes in hierarchy. Static Method is used if Base class needs to keep count of instances of all it’s subclass too.

class Base:
numOfInstances = 0
def __init__(self):
Base.numOfInstances += 1
def getNumInstances():
print Base.numOfInstances
getNumInstances = staticmethod(getNumInstances)
class Derived(Base):
def __init__(self):
Base.__init__(self)
b1 = Base()
d1 = Derived()
d2 = Derived()
d1.getNumInstances()
#It should print 3
Base.getNumInstances()
#It should print 3

20. Write a class which will count the number object created of that class.USING CLASS METHOD:

class Base:
numOfInstances = 0
def countInstances(cls):
cls.numOfInstances += 1
countInstances = classmethod(countInstances)
def getNumInstances(cls):
print cls.numOfInstances
getNumInstances = classmethod(getNumInstances)
def __init__(self):
self.countInstances()
class Derived(Base):
numOfInstances = 0
def __init__(self):
Base.__init__()

b1 = Base()
b2 = Base()
d1 = Derived()
d2 = Derived()
d3 = Derived()
b1.getNumInstances()
Base.getNumInstances()
#Both should print 2
d1.getNumInstances()
Derived.getNumInstances()
#Both should print 3

21. Given a list and a number find two numbers in the list that sums up to the number given?

a = [1,2,3,4,5,6,8] given_no = 9
mm = [] count =0
for x,y in enumerate(a):
for j in range(x+1, len(a)):
total_of_two_items = a[x] + a[j] if total_of_two_items == given_no:
mm.append((a[x],a[j]))
print mm

22. Difference between mutable and immutable  Mutable :

list, dict, set, byte array Immutable :
int, float, complex, string, tuple, frozen set ,bytes
x = 10
x = y
We are creating an object of type int. identifiers x and y points to the same object.
id(x) == id(y)
id(y) == id(10)
if we do a simple operation.
x = x + 1
Now
id(x) != id(y)
id(x) != id(10)
The object x is changed. object 10 was never modified. Immutable objects does not allow modification after creation of objects
In the case of mutable objects-
m = list([1, 2, 3])
n = m
We are creating an object of type list. identifiers m and m tagged to the same list object, which is a collection of 3 immutable int objects.
id(m) == id(n)
Now pop an item from list does change the object, m.pop() object id will not be changed id(m) == id(n) m and n are pointing to the same list object after the modification. The list object will be [1, 2].
* Python handles mutable and immutable objects differently.
* Immutable are quicker to access than mutable objects.
* Mutable objects are used when you need to change the size of the object, eg list, dict etc.. Immutables are used when you need to ensure that the object you have created will always stay the same.
* Immutable objects are expensive to “change”, because that involves creating a copy. Changing mutable objects is cheap.

23. Which is the shortest way to read a file?

Two memory efficient ways in ranked order (first is best) –
1. use of with – supported from python 2.5 and above

2. use of yield if you really want to have control over how much to read

1.USE OF WITH with statement is the nice & efficient way to read large files. advantages –

1) file object is automatically closed after exiting from with block.
2) exception handling inside the with block.
3) memory for loop iterates through the f file object line by line. internally it does buffered IO and memory management.

with open(“x.txt”) as f:
for line in f:
do something with data
The with statement handles opening and closing the file and also if an exception is raised in the inner block. The for line in f is the file object f as an iterable, which automatically uses buffered IO and memory management so you don’t have to worry about large files.

2. USE OF YIELD Sometimes one might want more fine-grained control over how much to read in each iteration. In that case use iter & yield. Note with this method one explicitly needs close the file at the end.
def readInChunks(fileObj, chunkSize=2048):
“””
Lazy function to read a file piece by piece.
Default chunk size: 2kB.
“””
while True:
data = fileObj.read(chunkSize)
if not data:
break
yield data
f = open(‘bigFile’)
for chuck in readInChunks(f):
do_something(chunk)
f.close()

24. Why is <__init__.py> module used in Python?

The <__init__.py> module can help in fulfilling 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 with the control to decide which directory is a package and which is not.

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.

25. Which methods of Python are used to determine the type of instance and Inheritance?

Python has two built-in functions that work with inheritance:
* isinstance() – this method checks the type of instance.
o for eg, isinstance(myObj, int) – returns True only when “myObj. class ” is “int”.
* issubclass() – this method checks class inheritance.
o for eg: issubclass(bool, int) – returns True because “bool” is a subclass of “int”.
o issubclass(unicode, str) – returns False because “unicode” is not a subclass of “str”.

26. Conditional Import in Python

For example you could except the ImportError exception:
try:
from Pyside2 import QtCore, QtGui
except ImportError:
from PySide import QtCore, QtGui
Alternatively, you can use the importlib module:
import importlib
import sys
PySide = importlib.import_module(‘Pyside2’ if ‘Pyside2’ in sys.modules else ‘PySide’)

27. Differentiate between “*.py” file nad “*.pyc” file?

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 the performance. The .pyc file is having bytecode which is platform independent. It can be executed on any operating system that supports .pyc format.
Note: there is no difference in speed when program is read from .pyc or .py file; the only difference is the load time.

28. 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 dept”
5. fetch the data using fetch() methods and print it. data = c1.fetch(s)
6. close the database connection. db.close()

29. Explain about ODBC and Python ?

ODBC (“Open Database Connectivity) API standard allows the connections with any database that supports the interface, such as PostgreSQL database or Microsoft Access in a transparent manner . There are 3 ODBC modules for Python:
1. PythonWin ODBC module – limited development
2. mxODBC – commercial product
3. pyodbc – it is an open source Python package.

30. How to define a protected member in a Python class?

All the members of a class are public by default in Python. You don’t need to define an access specifier for members of class. By adding `_` as prefix to the member of a class. By adding this convention you are telling others please don’t use this object, if you are not a subclass the respective class.
Eg: class Person:
empid = None
_salary = None #salary is a protected member & it can accessible by the subclasses of Person

31. How do you remove duplicates from a list?

a. sort the list
b. scan the list from the end.
c. while scanning from right-to-left, delete all the duplicate elements from the list

32. How do you check if file exists and their types in Python?

os.path.exists() – use this method to check if a file exists or not. It will return True if the file exists, false otherwise. Eg: import os; os.path.exists(‘/home/abc’)
os.path.isfile() – this method is used to check whether the give path is a file or not. It will return True if t the file exists , else it will return false. Eg: import os; os.path.isfile(‘/home/abc’)
os.path.isdir() – this method is used to check whether the give path references a directory or not. It will return True if the directory exists, else it will return false. Eg: import os;
os.path.isfile(‘/home/abc’)
os.path.getsize() – returns the size of the given file os.path.getmtime() – returns the timestamp of the given path.

33. How are the functions help() and dir() different?

help() and dir() are the 2 functions which you can access from Python Interpreter(terminal). These 2 functions are used for viewing a dump of built-in functions.
help() – it will display the documentation string. It is used to see the help related to modules, keywords, attributes, etc.

To view any help related to string type execute a statement
help(str) – it will display the documentation for ‘str, module.
Ex:
>>>help(str) or
>>>help() – it will open the prompt for help as help>
to view help for a module, help> module module name Inorder to view the documentation of ‘str’ at the help>, type help>modules str

to view help for a keyword, topics, you need to type, help> “keywords python-keyword” and “topics list”
dir() – will display the defined symbols.
Ex: >>>dir(str) – will only display the defined symbols.

34. Does the functions help() and dir() list the names of all the built_in functions and variables? If no, how would you list them?

The answer is No. So the builtin functions for eg max(), min(), filter(), map(), etc they are functions of standard module.To view them, we can pass the module ” builtins ” as an argument to “dir()”. It will display the all builtin exceptions, functions, and other objects as a list. For eg, >>dir(__builtins )  [‘AssertionError’,‘ArithmeticError’, ‘AttributeError’, ……… ]

35. How to make class iterable

Iterator objects in python conform to the iterator protocol, which basically means they provide two methods:
__iter__() and next().

The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment.
next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.
Here’s a simple example of a counter:

class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self): # Python 3: def
__next__(self)
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current – 1
for c in Counter(3, 8):
print c
This will print:
3
4
5
6
7
8

36. Whenever Python exists Why does all the memory is not de-allocated or freed when Python exits?

Whenever Python exists, especially those python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always deallocated/freed/uncollectable.
It is not possible to deallocate those parts of memory that are reserved/booked by libraries in C. On exit, because of having its own efficient deallocation mechanism, Python would try to deallocate/ destroy every object.

37. Explain Python’s zip() function.?

zip() function- it will take multiple lists say list1, list2, etc and convert them into a single list of tuples by taking their corresponding elements of the lists that are passed as parameters.

Eg:
list1 = [‘A’,
‘B’,’C’] and list2 = [10,20,30].
zip(list1, list2) # results in a list of tuples say
[(‘A’,10),(‘B’,20),(‘C’,30)] whenever the given lists are of different lengths, zip stops generating tuples when the first list ends.

38. There are given 2 numbers (where 6 can also be written as 5, and 5 as 6), #WAP to calculate the maximum and minimum possible sum

import copy
x = 645
y = 666
dig1 = list(str(x))
dig2 = list(str(y))
bb = [] vv = [] for i,j in enumerate(dig1):
temp1 = [] if j == ‘5’ or j == ‘6’:
temp1 = copy.deepcopy(dig1)
if j == ‘5’:
temp1[i] = ‘6’
else:
temp1[i] = ‘5’
bb.append(”.join(temp1))

for k,l in enumerate(dig2):
temp2 = [] if l == ‘5’ or l == ‘6’:
temp2 = copy.deepcopy(dig2)
if l == ‘5’:
temp1[k] = ‘6’
else:
temp1[k] = ‘5’
vv.append(”.join(temp2))
nn = zip(bb,vv)
aa = [] for no in nn:
temp = list(no)
aa.append(int(temp[0])+int(temp[1]))
print aa
print “max=” + str(max(aa))
print “min=” + str(min(aa))

39. Explain Python’s pass by references Vs pass by value . (or) Explain about Python’s parameter passing mechanism?

In Python, by default, all the parameters (arguments) are passed “by reference” to the functions. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function.We can see the pass “by value” kind of a behaviour everytime we pass arguments to the functions that are of type say strings, numbers, tuples. This is because of the immutable nature of them.

40. Explain how to overload constructors or methods in Python.

This is how you can overload the constructors Python constructor – _init__ () is a first method of a class. Every time we try to instantiate an object __init__() is automatically invoked by
python to initialize members of an object.

41. Explain the shortest way to open a text file and display its Contents.?

The shortest way to open a text file is by using “with” command as follows:
with open(“file-name”, “r”) as fp:
fileData = fp.read()
#to print the contents of the file print(fileData)

42. Fill in the missing code:

def print_directory_contents(sPath):
“””
This particular function takes the name of a directory and prints the paths files within that directory as well as any files contained in the contained directories.
This function is similar to os.walk. Please don’t use os.walk in your answer. We are interested in your ability to work with nested structures.
“””
fill_this_in Answer
def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)

43. Determine the o/p of following

A0 = dict(zip((‘a’,’b’,’c’,’d’,’e’),(1,2,3,4,5))) =======> {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘e’: 5, ‘d’: 4}
zip((‘a’,’b’,’c’,’d’,’e’),(1,2,3,4,5)) ==========> [(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4), (‘e’, 5)] dict(zip((‘a’,’b’,’c’,’d’,’e’),(1,2))) =======> {‘a’: 1, ‘b’: 2}
A1 =range(10) ========> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

A2 =sorted([i for i in A1 if i in A0])========> [] A3 =sorted([A0[s] for s in A0])========> [1, 3, 2, 5, 4] A4 =[i for i in A1 if i in A3]========> [1, 2, 3, 4, 5] A5 ={i:i*i for i in A1}========> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 =[[i,i*i] for i in A1]========> [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

44. What does this stuff mean: *args, **kwargs? And why would we use it?

We can use *args when we are not sure how many args we are going to pass to a function. We can also use if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will
be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The *args and **kwargs are a convention.You can also use *abc and **wxyz .
Below is the Eg:
def f(*args,**kwargs): print(args, kwargs)
l = [1,2,3] t = (4,5,6)
d = {‘a’:7,’b’:8,’c’:9}
f()f(1,2,3)
# (1, 2, 3) {}
f(1,2,3,”groovy”)
# (1, 2, 3, ‘groovy’) {}
f(a=1,b=2,c=3)
# () {‘a’: 1, ‘c’: 3, ‘b’: 2}
f(a=1,b=2,c=3,zzz=”hi”)
# () {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘zzz’: ‘hi’}
f(1,2,3,a=1,b=2,c=3)
# (1, 2, 3) {‘a’: 1, ‘c’: 3, ‘b’: 2}
f(*l,**d)
# (1, 2, 3) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f(*t,**d)
# (4, 5, 6) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f(1,2,*t)
# (1, 2, 4, 5, 6) {}
f(q=”winning”,**d)
# () {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
f(1,2,*t,q=”winning”,**d) # (1, 2, 4, 5, 6) {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
def f2(arg1,arg2,*args,**kwargs): print(arg1,arg2, args, kwargs)
f2(1,2,3)
# 1 2 (3,) {}
f2(1,2,3,”groovy”)
# 1 2 (3, ‘groovy’) {}
f2(arg1=1,arg2=2,c=3)
# 1 2 () {‘c’: 3}
f2(arg1=1,arg2=2,c=3,zzz=”hi”) # 1 2 () {‘c’: 3, ‘zzz’: ‘hi’}
f2(1,2,3,a=1,b=2,c=3)
# 1 2 (3,) {‘a’: 1, ‘c’: 3, ‘b’: 2}
f2(*l,**d)
# 1 2 (3,) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f2(*t,**d)
# 4 5 (6,) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f2(1,2,*t)
# 1 2 (4, 5, 6) {}
f2(1,1,q=”winning”,**d)
# 1 1 () {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
f2(1,2,*t,q=”winning”,**d) # 1 2 (4, 5, 6) {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}

45. What are @classmethod, @staticmethod, @property?

A decorator is a special kind of function that takes a function and returns a function, or takes a class and returns a class. The @ symbol is just syntax that allows you to decorate something in a way that’s easy to read.
@my_decorator
def my_func(stuff):
do_things
Is equivalent to
def my_func(stuff):
do_things
my_func = my_decorator(my_func)
Actual Answer
The decorators @classmethod, @staticmethod and @property are used on functions defined within classes. Here is how they behave:
class MyClass(object):
def __init__(self):
self._some_property = “properties are nice”
self._some_other_property = “VERY nice”
def normal_method(*args,**kwargs):print(“calling normal_method({0},{1})”.format(args,kwargs))
@classmethod
def class_method(*args,**kwargs):
print(“calling class_method({0},{1})”.format(args,kwargs))
@staticmethod
def static_method(*args,**kwargs):
print(“calling static_method({0},{1})”.format(args,kwargs))
@property
def some_property(self,*args,**kwargs):
print(“calling some_property getter({0},{1},{2})”.format(self,args,kwargs))
return self._some_property
@some_property.setter
def some_property(self,*args,**kwargs):
print(“calling some_property setter({0},{1},{2})”.format(self,args,kwargs))
self._some_property = args[0] @property
def some_other_property(self,*args,**kwargs):
print(“calling some_other_property getter({0},{1},{2})”.format(self,args,kwargs))
return self._some_other_property
o = MyClass()
o.normal_method
# >
o.normal_method()
# normal_method((<__main__.myclass instance at>,),{})
o.normal_method(1,2,x=3,y=4)
# normal_method((<__main__.myclass instance at>, 1, 2),{‘y’: 4, ‘x’: 3})
# class methods always get the class ‘cls’ as the first argument
o.class_method
# >
o.class_method()
# class_method((,),{})
o.class_method(1,2,x=3,y=4)
# class_method((, 1, 2),{‘y’: 4, ‘x’: 3})
# static methods have no arguments except the ones you pass in when you call them
o.static_method
#
o.static_method()
# static_method((),{})
o.static_method(1,2,x=3,y=4)
# static_method((1, 2),{‘y’: 4, ‘x’: 3})
# properties are a way of implementing getters and setters. It is an error to call them explicitly
o.some_property
# calling some_property getter(<__main__.myclass instance at>,(),{})
# ‘properties are nice’o.some_property()
# calling some_property getter(<__main__.myclass instance at>,(),{})
# Traceback (most recent call last):
# File “”, line 1, in
# TypeError: ‘str’ object is not callable
o.some_other_property
# calling some_other_property getter(<__main__.myclass instance at>,(),{})
# ‘VERY nice’
# o.some_other_property()
# calling some_other_property getter(<__main__.myclass instance at>,(),{})
# Traceback (most recent call last):
# File “”, line 1, in
# TypeError: ‘str’ object is not callable
o.some_property = “groovy”
# calling some_property setter(<__main__.myclass object at>,(‘groovy’,),{})
o.some_property
# calling some_property getter(<__main__.myclass object at>,(),{})
# ‘groovy’

46. Write a program to find out the name of an object in python.

The object does not have any name and there is no way the can be found out for objects. The assignment is used to bind a name to the value,it has the name of the object that has to be bound by a value. If the value is callable then the statements are made true.Then the program followed can be used to find the reference name of an object. class try:pass
B = A
a = B()
b = a
print b
<__main__.try instance at>
print b
The class consists of name and names are invoked by using the the variable B which creates an instance for the class try.

47. Write a program to check whether the object is of a class or its subclass.

There is a builtin method which is to show the instances of an object that consists of many classes by providing a tuple in a table instead of individual classes. The method is written as is instance(obj,cls) and in more details written as: isinstance(obj, (class1, class2, …)) it checks that the object’s presence in one of the classes. The built in types can also have many formats of the same function for eg isinstance(obj, str) or isinstance(obj, (int, long, float, complex)).

It is not preferred to use the class instead of user-defined class. These perform different thing that is based on the class. The function differs from one class to another class.
To find out the object of the particular class the following program is used:

def search(obj):
if isinstance(obj, box):
# This is the code that is given for the box and write the program in the object
elif isinstance(obj, Document):
# This is the code that searches the document and writes the values in it
elif
obj.search()
#This is the function used to search the object’s class.

48. What is the use of join() for a string rather than list or tuple method?

The functions and the methods that are used for the functionality uses the string module. This is represented as by using the join function in it:
“, “.join([‘1’, ‘2’, ‘4’, ‘8’, ’16’]) that results in “1, 2, 4, 8, 16”
The string var that is used provide a fixed string to allow the names that are used to be bounded to the strings. join() is a string method that is used to provide a separator string to use the function over the sequence of the string and insert the function to an adjacent elements. This method uses any number of args that follow some rules. The ‘join’ is used for string module that is used to join the string characters together.

For Eg: string.join([‘1’, ‘2’, ‘4’, ‘8’, ’16’], “, “)

49. What are the steps required to make a script executable on Unix?

The steps which are required to make any script executable are to:
– First create a script file and write the code that has to be executed in it.
– We need to make the file mode as executable by making the first line starting with #! this is the line that python interpreter reads.
– Set the permission for the file by using chmod +x file. The file uses the line that is the most important line to be
used:
#!/usr/local/bin/python
– The above line explains that the pathname that is given to the python interpreter and it is independent of the environment programs.
– The file’s Absolute pathname should be given so that the interpreter can interpret and execute the code accordingly. The
sample code that is written:
#! /bin/sh
# Write your code here
exec python $0 ${1+”$@”}
# Write the function that need to be included.

50. Write a program to read and write the binary data using python?

The module that is used to write and read the binary data is known as struct.. This class contains the binary data. It is in the form of numbers.It gets converted in python objects for use and vice versa. The program can read or write the binary data is:
import struct
f = open(file-name, “rb”)
# Open() method allows the file to get opened in binary mode.
s = f.read(8)
x, y, z = struct.unpack(“>hhl”, s)
The ‘>’ is used to show the format string that allows the string to be converted in big data form. For homogenous list of data the array can be used that will allow the data to be kept more in organized fashion.

51. Write a program to show the singleton pattern used in python.

Singleton pattern is used to provide a mechanism that limits the number of instances that can be used by one class. This also allows the same object to be shared in many different parts of the code. This allows the global variables to be used as the actual data which is used is hidden by the singleton class interface. The singleton class interface can have only one public member and one class method Handle. Private constructors are not used to create an object that is used outside the class. The process waits for the static member function to create new instances and return the singleton object.
The code that is used to call the singleton object is:
Singleton& Singleton::Handle()
{
if( !psingle )
{
psingle = new Singleton;
}
return *psingle;
}

52. What does _init_.py do?

_init_.py is an empty py file which is used for importing a module in a directory. _init_.py provides an easy way to organize the files. If there is a module maindir/subdir/module.py,_init_.py is placed in all the directories so that the module can be imported using the following command- import maindir.subdir.module

53. You are given a list of N numbers. Create a single list comprehension in Python to create a new list which contains only those values which have even numbers from elements of the list at even indices.

For instance if list[4] has an even value the it has be included in the new output list because it has an even index but if list[5] has an even value it should not be included in the list because it is not at an even index.
[x for x in list [: 2] if x%2 == 0] The above code will take all the numbers present at even indices and then discard the odd numbers.

54. What will be the output of the below Python code?

def xyz ():
return [lambda x: i * x for i in range (4)] print [m (2) for m in xyz ()] The output for the above code will be [6, 6,6,6]. The reason for this is that because of late binding the value of variable ‘i’ is looked up when any functions returned by ‘xyz’ are called.

55. What do you mean by list comprehension?

The dynamic process of creating a list while performing some operation on the data so that it can be accessed using an iterator is referred to as List Comprehension.
Example:
[ord (j) for j in string.ascii_uppercase] [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]

56. What will be the output of the below code?

word = ‘aeioubcdfg’
print word [:3] + word [3:] The output for the above code will be: ‘aeioubcdfg’.

57.How will you set a global variable inside a function?

You can use a global variable in other func’s by declaring it as global in each func 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 # No need for global
declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1

1
2
3
4
5
6
7
8
Global variables are so dangerous so Python wants to make sure that you really know that’s what you’re playing with by explicitly requiring the global keyword.

58. list= [1, 2 , 3 , 4 , 5 , 6 , 7 ]

print list [8:] The output for the above code will be an empty list []. Most people might get confused in the answer with an index error. Because the code is trying to access a member in the list whose index exceeds the total number of members in the list. The code is trying to access the slice of a list at a start index which is greater than the number of members in the list.

59. What will be the output of the below code:

def foo (i= []):
i.append (1)
return i
>>> foo ()
>>> foo ()The output for the above code will be-
[1] [1, 1] Argument to the function foo is evaluated only once when the function is defined. However, since it is a list, on every
all the list is modified by appending a 1 to it.

60. Find factors of a given no.

def factorial(n):
if n return 1
else:
temp = ”
for i in range(1,n+1):
if n % i == 0:
temp += str(i) +’,’
return temp
num = raw_input(“Enter any number: “)
print factorial(int(num))

The post Python Interview Questions & Answers appeared first on Besant Technologies | No.1 Training Institute in Chennai.



This post first appeared on Job Openings In Hcl, please read the originial post: here

Share the post

Python Interview Questions & Answers

×

Subscribe to Job Openings In Hcl

Get updates delivered right to your inbox!

Thank you for your subscription

×