Python Interview Questions and Answers

Python Interview Questions and Answers

Python Interview Questions and Answers

1) Which of the following 2 are Python DebugMode variables? (select 2)

Answer : a,b

2) Which is invalid for Warning variable?

Answer: b

3) Which one of the following identifier is not reserved keyword?

a) with
b) del
c) assert
d) null
Answer: d

4) What could be the Character with 32-bit hex value xxxxxxxx ?

a) \Xxxxxxxxx
b) \Hxxxxxxxx
c) \Uxxxxxxxx
d) \Oxxxxxxxx
Answer: c

5) Below code will delete the list variable a completely, True or False ?

del a[:] a) True
b) False
Answer: b

6) What is the output for the following?

for i, v in enumerate([‘a’, ‘e’, ‘i’,’o’,’u’]):
print(i, v)
a) Error
b) ‘i’ is not defined
c) 1 a, 2 e, 3 i, 4 o, 5 u
d) 0 a, 1 e, 2 i, 3 o, 4 u
Answer : d

7) Does Keyword arguments are possible in Dictionary type cast?

Is Below statement valid ?
dict(one=1, two=2, three=3)
a) Invalid
b) Valid
Answer: b

8) What will be the output for following code?

if((1, 2, 2)<(1, 2, 4)):
a) null
b) error
c) true
d) false
Answer: c

9) The Function dir() does not list the names of built-in functions and variables.

To list of those, Which standard module will you use ?
a) sys
b) builtins
c) trace
d) os
Answer: b

10) What will the output for following code ?

print(‘My name is {1}, working as {role}, and from {0}.’.format(‘India’, ‘Tom’,
a) Syntax Error
b) My name is Tom, working as Engineer and from India
c) Run-time Error
d) My name is India, working as and from India
Answer: b

11) What will the output for below code ?

print((30 – 3*6) / 2)
a) 6
b) 6.0
c) 81
d) Error
Answer: b

12) What will the output for below code ?

print(18 // 5)
a) 3.6
b) Syntax error
c) 3
d) 4
Answer: c

13) Below code is valid ?

a) True
b) False
Answer: a

14) What will be the output ?

a) C:\Users\naveen
b) Error
c) double quotes is right usage.
d) None of the above
Answer: d

15) What is the output for following code ?

print(2 * ‘ab’ + ‘ab’)
a) Syntax Error
b) ababab
c) ab2ab
d) 2abab
Answer: b

16) Python String rule: str[:i] + str[i:] is always equal to str

Where str is given string and i is index position.
a) False
b) True
Answer: b

17) What will be the output?

list1 = [1,2,3,4,5] print(list1[-3:])
a) Error. (slicing cannot be negative)
b) 3,2,1
c) 3,4,5
d) 5,4,3
Answer: c

18) Only Addition and multiplication operations on two given list is possible ?

a) True
b) False
Answer: b

19) What will happen after below code execution ?

List1[:] = [] a) Syntax Error
b) clears List1 with an empty list.
c) Index error
d) None of the above
Answer: b

20) Below code is valid ?

time = ‘Morning’
greet = ‘Good’
print( f’Hi {greet} {time}’)
a) False
b) True
Answer: b

21) Django-admin command is used to create the django App in django project.

Answer: b

22) What is the expansion of WSGI ?

a) Web services gateway interface
b) Web server gateway interface
c) Website services gateway Interface
d) None of the above
Answer: b

23) What will be the expected output ?

str = ” Hi, How are You! ”
a) Hi,HowareYou!
b) HiHowareYou
c) Hi, How are You! (Without space at begin or end)
d) strip function has mandatory arguments.
Answer: c

24) The code to convert the string to lower case.

str1 = Hello Buddy
Answer: c

25) PIP Command is used to manage python package. It has package search feature in online ?

Answer: a

26) PIP Command can install only one package at a time.

Answer: a

27) What will be the output for following code ?

>>> list1 = [5, 8] >>> list(range(*list1))
a) Error
b) [5,6,7] c) [5,] d) [5,8] Answer: b

28) Please find the odd-man out.

a) List
b) Tuples
c) Sets
d) Dictionaries
Answer: b

29) Please find the odd-man out.

a) Strings
b) Tuples
c) Numbers
d) List
Answer: d

30) What is expansion of GIL ?

a) Global Interpreter Language.
b) Global Interpreter Lock
c) Global Implementation Language
d) Global Implementation Lock
Answer: b

31) How random numbers can be generated ?

a) import random
b) import random
c) import numpy
d) import math.random
Answer: a

32) What is expansion of MVT?

a) Model Virtual Template
b) Model View Template
c) Machine View Template
d) Model View Tool
Answer: b

33) Below code is valid ?

import datetime
now = //now returns current time,
a) True
b) False
Answer: a
34) Which of below code is valid ?

a) 7//3 = 2
b) 7/3 = 2
c) 7//3 = 2.3333333333333335
d) 7/3 = 2.3333333333333335
Answer: d

35) Which of following statement is true regarding Finally clause ?

a) Executed in any event.
b) Executed only at end of except block.
c) Executed only at end of else block.
d) None of above
Answer: a

36) True or False ?

class Student
obj = Student()
This will create the empty Student record.
a) False
b) True
Answer: b

37) Which of following code will return present working directory?

a) os.getpwd()
b) os.pwd()
c) os.getcwd()
d) os.cwd()
Answer: c

38) To get list of all python files in wildcard search, which code will be valid ?

a) glob.glob(‘*.py’)
b) os.glob(‘*.py’)
c) os.glob.glob(‘*.py’)
d) os.get(‘*.py’)
Answer: a

39) Regarding following statement.

from urllib.request import urlopen
#This import statement is used for retrieve data from given URL.
a) True
b) False
Answer: a

40) Which of following is invalid ?

import logging
a) logging.debug(‘Hi’)
b) logging.error(‘Hi’)
d) logging.message(‘Hi’)
Answer: d

41) Output of following code ?

0.1 ** 2.5 *2
a) 0.00632455532033676
b) 0.020000000000000004
c) 0.025000000000000005
d) None
Answer: a

42) Output of following code ?

a) Syntax Error
b) 1.0
c) 1
d) None

43) Output of following code?

>>> [“AA”]*2
b) [‘AA’, ‘AA’] c) error
d) [“AAAA”] Answer: b

44) True or False?

>>> [3] + [5] [8] a) True
b) False
Answer: b

45) Output of following code?

>>> set_All = {1,2,3,4,5}
>>> set_Even = {2,4}
>>> set_odd = {1,3,5}
>>> print(set_All ^ set_odd)
a) {1,2,3,5}
b) {1,3,5}
c) {2, 4}
d) None of above
Answer: c

46) Output of following code?

>>> set1 = {1,2,3,4,5}
>>> set1[1:3] a) 1,2,3
b) 1,2
c) Error
d) {1,2}
Answer: c

47) Below code will create the empty set, True or False ?

a) False
b) True
Answer: a

48) What will be the ouput when we execute below code?

>>> dict1={‘Name’:’John’,’Age’:26,’Salary’:2000}
>>> dict1[1] a) {‘Age’:26}
b) 26
c) Syntax Error
d) Key Error
Answer: d

49) What can be the output ?

>>> dict1={‘Name’:’John’,’Age’:26,’Salary’:2000, ‘Name’:’Alex’}
>>> dict1[‘Name’] a) ‘John’
b) ‘Alex’
c) Key Error
d) [‘John’, ‘Alex’] Answer: b

50) Output will be,

>>> set1 = {1,3}
>>> set2 = {2,4}
>>> set1 & set2
a) {1,3,2,4}
b) {1,2,3,4}
c) set()
d) {}
Answer: c

51) Is set nesting implemented in Python?

Answer:It is implemented, but you need to use a hashable type instead. frozenset() is that type.

52) How can we make a executable file with Python script?


py2exe but it only works on Windows.
PyInstaller works on Windows and Linux
Py2app works on the Mac.

53) How do you convert a list of integers to a comma separated string?


List elements turned into a string using a join function.
>>> a = [1,2,3,4,5,6,7,8]

>>> numbers = ‘,’.join(str(i) for i in a)
>>> print(numbers)

54) Write one line of code to get a list of names that start with character ‘j’?

names = [‘john’, ‘fan’, ‘sam’, ‘megha’, ‘popoye’, ’tom’, ‘jane’, ‘james’,’tony’] Answer:
>>> names = [‘john’, ‘fan’, ‘sam’, ‘megha’, ‘popoye’, ‘tom’, ‘jane’, ‘james’, ‘tony’] >>> jnames=[name for name in names if name[0] == ‘j’] #One line code to filter names that start with ‘j’
>>> jnames
[‘john’, ‘jane’, ‘james’]

55) How do you get the last value in a list or a tuple?

Answer:When we pass -1 to the index operator of the list or tuple, it returns the last value. If -2 is passed, it returns the last but one value.
>>> a = [1,2,3,4] >>> a[-1] 4
>>> a[-2] 3
>>> b = (1,2,3,4)
>>> b[-1] 4
>>> b[-2] 3

56) How to check whether a module is installed in Python?


import sys
“module_name” in sys.modules
import random
“random” in sys.modules
>> True

57) How do you find the number of references pointing to a particular object?


The getrefcount() function in the system module give the number of references pointing to a particular object including own reference.
>>> a = “PrasantMishra”
>>> b = a
>>> sys.getrefcount(a)
Here, the object ‘PrasantMishra’ is referred by a, b and getrefcount() function itself. So the output is 3.

58) How do you convert a list of integers to a comma separated string?

Answer: List elements can be turned into a string using join function.
>>> a = [1,2,3,4,5,6,7,8] >>> numbers = ‘,’.join(str(i) for i in a)
>>> print(numbers)

59) Write one line of code to get a list of names that start with character ‘j’?

names = [‘john’, ‘fan’, ‘sam’, ‘megha’, ‘popoye’, ’tom’, ‘jane’, ‘james’,’tony’] Answer:
>>> names = [‘john’, ‘fan’, ‘sam’, ‘megha’, ‘popoye’, ‘tom’, ‘jane’, ‘james’, ‘tony’] >>> jnames=[name for name in names if name[0] == ‘j’] #One line code to filter names that start with ‘j’
>>> jnames
[‘john’, ‘jane’, ‘james’]

60) How to count the occurrences of a particular element in the list?


a) weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’] print(weekdays.count(‘mon’))
b) weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’] print([[x,weekdays.count(x)] for x in set(weekdays)])

61) How Can I Find The Methods Or Attributes Of An Object?

Answer:For a instance z of a user-defined class, dir(z) returns an alphabetized list of the names containing the methods and instance attributes and attributes defined by its class.

62) What is

Answer: It is used to import a module in directory, which is called as package import.
If we have a module,
dir1/dir2/, we put in each directories so that we can import the module like this:
import dir1.dir2.mod
The is usually an empty py file. The hierarchy gives us a flexible way of organizing the files in a large system.

63) What mode is used for both writing and reading in binary format in file.?

Answer: wb+ mode is used to both writing and reading in binary format in file. It overwrites if the file exists. If the file does not exist it creates a new file for writing and reading.

64) What is for-else and while-else in Python?

Answer: Python provides a way of handling loops by providing a function to write else block in case the loop is not satisfying the condition.
a = [] for i in a:
print “in for loop”
print “in else block”
in else block
The same is true with while-else too

65) What is the function of GIL in Python?

Answer: In Python, the global interpreter lock, or GIL, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once.
Basically it prohibits more than 2 processes or threads to access a memory location in Python parallely.

65) What is the key difference between Java and Python?

Answer: Java is a static data type,
Python is a dynamic typed-data type.

66) What Does The Ord() Function Do In Python?

Answer: The ord() in Python takes a string of size one and returns an integer denoting the Unicode code format of the character in case of a Unicode type object, or the byte value as if the argument is of 8-bit string type.
>>> ord(“z”)

67) What Does The **kwargs do In Python?


# Python code to demonstrate
# **kwargs for dynamic + named arguments
def fn(**kwargs):
for emp, age in kwargs.items():
print (“%s’s age is %s.” %(emp, age))
fn(John=25, Kalley=22, Tom=32)
The output:
John’s age is 25.
Kalley’s age is 22.
Tom’s age is 32.

68) What Does The *args do In Python?


# Python code to demonstrate
# *args for dynamic arguments
def fn(*argList):
for argx in argList:
print (argx)
fn(‘I’, ‘am’, ‘Learning’, ‘Python’)
The output:

69) What is the difference between useing a for loop in the following types:


a = [1,2,3,4] for i in a: pass
for i in range(len(a)): pass
for i in a: iterates the list with the values
for i in range(len(a)): iterates the list using the indices

70) What Do You Think Is The Output Of The Following Code Fragment? Is There Any Error In The Code?


list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] print (list[10:])
The result is the above lines of code is []. There won’t be any error like an IndexError.

71) What is the meaning of @classmethod and @staticmethod ?


@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use class and properties inside that method rather than a particular instance.
@staticmethod means: when this method is called, we don’t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can’t access the instance of that class (this is useful when your method does not use the instance).

72) How do I access environment variables from Python?


import os
print(os.environ[‘HOME’]) # HOME is one of the environment variable
import os
for a in os.environ:
print(‘Var: ‘, a, ‘Value: ‘, os.getenv(a))

73) How to convert bytes to a string?


>>> b”abcde”
* utf-8 is used here because its a very common encoding, but you
need to use the encoding your data is actually here,
>>> b”abcde”.decode(“utf-8”)

74) How to call a function of a module by using its name (a string)?


module = __import__(‘foo’)
func = getattr(module, ‘bar’)

75) How to determine type of an object?


>>> type([]) is list
>>> type({}) is dict
>>> type(”) is str
>>> type(0) is int
>>> type({})
<type ‘dict’>
>>> type([])
<type ‘list’>

76) How to delete a file or folder?


import os
os.remove() # removes a file.
os.rmdir() # removes an empty directory.
shutil.rmtree() # delete a directory and all its contents.
pathlib.Path.unlink() # removes the file or symbolic link.
pathlib.Path.rmdir() # removes the empty directory.
import os
## If file exists, delete it ##
if os.path.isfile(myfile):
else: ## Show an error ##
print(“Error: %s file not found” % myfile)

77) Since switch-case is not used in Python – what are the replacements for switch statement in Python?


class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
def case(*args):
return any((arg == switch.value for arg in args))
while switch(n):
if case(0):
print “You typed zero.”
if case(1, 4, 9):
print “n is a perfect square.”
if case(2):
print “n is an even number.”
if case(2, 3, 5, 7):
print “n is a prime number.”
if case(6, 8):
print “n is an even number.”
print “Only single-digit numbers are allowed.”

78) How to convert a string into datetime?


from datetime import datetime
datetime_object = datetime.strptime(‘Aug 8 2009 8:44AM’, ‘%b %d %Y %I:%M%p’)
from dateutil import parser
dt = parser.parse(“Aug 28 1999 12:00AM”)

79) In python, how do copy a file?


# In Linux/Unix
os.system(‘cp source.txt destination.txt’)
# In Windows
os.system(‘copy source.txt destination.txt’)

80) How to concatenate two lists in Python?


a) listone = [1,2,3] listtwo = [4,5,6] mergedlist = listone + listtwo
>>> mergedlist
[1,2,3,4,5,6] b) mergedlist = list(set(listone + listtwo))

81) In python,How to read a file line-by-line into a list?


with open(fname) as f:
content = f.readlines()
# you also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]

82) How to clone or copy a list?

newlist = old_list.copy()

83) How to get the current time in Python?


>>> import datetime
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(
2018-07-29 09:17:13.812189
And just the time:
datetime.time(15, 8, 24, 78915)
>>> print(

84) How can I make a time delay in Python?


import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.

85) Difference between __str__ and __repr__?


__repr__() is invoked when you simplified write object’s name on interactive python console and press enter.
__str__() is invoked when will you use object with print statement.

86) How to find the index of an item given a list containing it in Python?


a) >>> [“foo”, “bar”, “baz”].index(“bar”)
b) >>> [1, 1].index(1)
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1] [0, 2]

87) How do I list all files of a directory?


a) import os
b) import os
# Getting the current work directory (cwd)
thisdir = os.getcwd()
# r=root, d=directories, f = files
for r, d, f in os.walk(thisdir):
for file in f:
if “.docx” in file:
print(os.path.join(r, file))
c) >>> import os
>>> arr = os.listdir(‘F:\\python’)
>>> arr
[‘$RECYCLE.BIN’, ‘work.txt’, ‘3ebooks.txt’, ‘documents’]

88) In python,How do I check if a list is empty?


if not a:
print(“List is empty”)

89) Does Python have a string ‘contains’ substring method?


in operator
a) >>> “King” in “King’s landing”
>>> “Jon Snow” in “King’s landing”
b) >>> some_string = “valar morghulis”
>>> some_string.find(“morghulis”)
>>> some_string.find(“dohaeris”)

90) How do I sort a dictionary by value?


  • sorted([(value,key) for (key,value) in mydict.items()])
  • sorted((value,key) for (key,value) in mydict.items())

91) How to call an external command in Python?


a) from subprocess import call
call([“ls”, “-l”])
b) import os
cmd = ‘ls -al’
import os
os.system(“your command”)
The advantage of subprocess vs. system is that it is more flexible (you can get the stdout, stderr, the “real” status code, better error handling, etc…).

92) How do I check whether a file exists without exceptions?


>>> print os.path.isfile(“/etc/password.txt”)
>>> print os.path.isfile(“/etc”)
>>> print os.path.isfile(“/does/not/exist”)
>>> print os.path.exists(“/etc/password.txt”)
>>> print os.path.exists(“/etc”)
>>> print os.path.exists(“/does/not/exist”)
import os.path
if os.path.isfile(filepath):
import os
os.path.exists(path) # Returns whether the path exists or not
os.path.isfile(path) # Returns whether the file exists or not

93) Does Python have a ternary conditional operator?


Python has a ternary operator after the version 2.5
>>> ‘true’ if True else ‘false’
>>> ‘true’ if False else ‘false’
it works like : [expression] and [on_true] or [on_false]

94) What does the ‘yield’ Keyword do?


yield is a keyword, yield is used like return, except the function will be return a generator.
>>> def createGenerator():
… mylist = range(3)
… for i in mylist:
… yield i*i

>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
… print(i)

95) How can I wait until we receive data using Python Socket?


Using s.accept(), the client will wait till a client accepts the connection before starting the while loop to receive data.
connection before starting the while loop to receive data. This should help with your problem.
def receiver():
PORT = 123
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((‘’, PORT))
conn,address=s.accept() # accept incoming connection by using accept() method which will block until a new client connects
while True:
datachunk = conn.recv(CHUNK_SIZE) # reads data chunk from the socket in batches using method recv() until it returns an empty string
if not datachunk:
break # no more data coming , so break can out of the while loop
data.append(datachunk) # add chunk to your already collected data

96) What are the immutable build-in data types of python?


These are the immutable build-in datatypes in Python.

  • Numbers
  • Strings
  • Tuples

97) What are the types of Basic Functions in python?

There are the types of Basic Functions in python.

  • Build-in Function
  • User-defined Function

98) Write a sample program in enumerate()function in python?


for i, subject in enumerate(subjects):
Print(i, Subject)
0 c
1 c++
2 Python

99) List Some Namespace in python.


There are main four namespace in python.

  • Global
  • Local
  • Module
  • Class Name spaces

100) What is python namespace

Answer: Name spaces contain all built-in names. Namespaces are used to avoid ambiguity and make it unique. python name space are built in python dictionary that is key value pairs. Basically name is referred to the object name


nameA={ ‘var_name1’=object1, ‘var_name2’=object2, …}
nameB={ ‘var_name1’=object3, ‘var_name2’=object5, ‘var_name3’=object6, …}

The names can be similar in both namespaces because they are assigned to different objects

101) How many name spaces are defined in python

Answer:There are 3 name spaces are defined in python

  • Built name space
  • Module: Global name spaces
  • Function: Local name spaces

102) Can we use else block with for loop? Answer with one example.

Answer:Yes, we can use else block with for loop. when the loop has successfully iterated then the else block is going to execute


my_list=[‘c’,’c++’,’Java’,’Python’,’C#’] for i in my_list:
print(‘The elements are in the list is’,i)
print(‘The iteration is successfully done ’)

103) Where we can use else block in python programming

Answer:We can use else block with if, for, while, try etc..

104) Explain about dir() and help() function will do in python

Answer: dir() is used to display the all the methods of a particular object

Example 1: dir(list)

This will display the all the functions which we can perform on the list object

help() is very useful function in python which will tell us the documentation about the given object or method or attribute

Example 2: help(list.append)

105) Explain about python break, continue and pass.

Answer:Break, continue and pass are the keywords in python, which we will use in different scenarios as per the logic.

break will stop the for loop or while loop if these loops fall into the a particular case. Generally we use break to stop the looping execution

Example 1:

for  in ‘Besant Technologies’:
If i==’o’:

continue statement use when we don’t want to execute the particular case and skip that iteration

Example 2:

for  in ‘Besant Technologies’:
If i==’o’:

pass is a keyword which we use it for make any function or class is syntactically valid

Example 3:

class BesantTechnologies(branch):


106) Explain ternary operator in python

Answer: Ternary operator will   reduce the code and increase the readability of a script. there is no special operator for ternary, we can write it

Example 1:

Animal=’Dog’ if is_animal else ‘Tree’

Example 2:

print([x if x>y else y])

107) what is python main function and write one good example

Answer: Main function is entry point to the python program


print(“__name__ value: “, __name__)
def main():
print(“python main function”)
if __name__ == ‘__main__’:

108) what is print format value interpolation

Answer: Using the formatted output we can easily insert the variable in the print statement for output

We can use .format() method for interpolation

Below is the example given


print(‘{}is the city in the {}’.format(b,a))

we can give the order of preference also

109) what is pip and pip freeze commands will do

Answer: Pip is python package installer which will preinstalled with python3.we use pip to install any third party libraries to our python software.


if I want to install xlrd module

pip install xlrd

and pip freeze command is used to check which modules has installed on my system and will show the version numbers also

ex: pip freeze

110) what is random module is in python

Answer: Random module will generate a random number from the given range. we can import random module from python preinstalled libraries.


Import random
print(random.randrange(a, b, 10))

111) Explain about zip() in python

Answer: Python zip function is used to combine iterable data types of same length. python tuple will be the output of the zip function


data=[1,2,3,4] data2=[5,6,7,8] test=zip(data,data1)

112) Explain class __init__()

Answer: Class __init__ method is called special method to initialize the attributes of a class. when ever we create an object of the class the __init__ gets called and assigned the is mandatory in every class. Sometimes we call it as constructor method also.

113) What is meta class in python

Answer: Generally, in python everything is an object, and everything belongs to one of the class.

And this class is also an object of another class. This another class is called meta class. It defines the behavior of class objects


type() is built-in meta class

114) Explain the difference between append vs extend in list

Answer: Append and extend are the built-in functions for list. These two functions are going to add some new element/elements to the list object

append() will add one element at a time

extend will add list of elements to the existing list

ex: Data=[1,2,3,4,5,6]






append will always add the new element at the end of the list

if we want to add the element in the middle we have to use insert()

115) Whats the difference between input() and raw_input()

Answer: We use these two functions in two different versions of python.

raw_input() specific to python 2.X version, which we use to take the user input in the format of string

input() in 2.x takes the integers

input(), Generally we use in 3.X version to take the input from the user. By default input() will gives you the data in the form of string. When ever we require to change to int or float we need to change it explicitly. This is called type casting in python

116) What is raise keyword do in python exception handling

Answer: Raise is keyword used to raise the user exceptions in try catch block

117) Explain about pdb module in python

Answer: Python debugger is internal module which will give good feature for effective debugging.We can see the step by step execution and variable assignments and even pause the program using this pdb.

For example, if you have a program to debug, we can execute program in following manner


python -m pdb

118) Tell us something about Garbage collector in python

Answer: Garbage collector is a memory management mechanism in python. It is a process of deallocating memory when the object has no reference to it

Below is the example explains the garbage collector

class BesantTechnologies():
def __del__(self):
print(“No reference left for {}”.format(self))
user1 = BesantTechnologies()
user2 = user1
user3 = user1
when we deallocate the objects like this
No reference left for <__main__.User object at 0x212bee9d9>

119) Write a program to find the duplicates in a list

Answer: Let’s take the list

New_list=[22,33,44,55,21,22,55,98,56,44] Original=[] for i in New_list:
if i not in original:

Note: We can achieve the above program using set datatype also

120) Write a program to find the max value from a list without using max()


X=[12,31,45,32,67,32,21,45,2] Max=0
for i in x:
if i>Max:

121) Write program to find the common elements from two sets



122) Write a program to play a guessing game using random module


import random
y=int(input(‘Guess your number’))
while y!=x:
print(‘Wrong Guess…try one more’)
y=int(input(‘Guess your number’))
print (‘Congrats! , You have guessed it correctly’)

123) Write program to validate the email address in python


import re

124) Write a program to create a class and make an object of the class in python


Class dog():
def __init__(self,color,breed):
def eat(self):
print(“This is dog eating..”)
def bark(self):
print(“This is dog bark”)

125) What is self in OOP of python

Answer: The self in python is mandatory in every method defined in class. The self represents the same class object. Python will not use @ symbol to refers to the instance variables. Instead python uses self parameter .

126) What is the output of the below program

def f(x,l=[]):
for i in range(x):


[0, 1] [3, 2, 1, 0, 1, 4]    [0, 1, 0, 1, 4]

127) Explain what is decorator

Answer: A decorator is a function which modify or add the functionality of another functions with out modifying it. It will wrap another function to modify the functionality


def decor(func):
def wrap():
def sayhi():

128) Write a program to check for prime number


y=int(input(‘Guess your number’))
for i in range(2,y):
if y%i==0:
print(‘The given number is not a prime’)
print(‘The given number is prime’)

129) Write a program to reverse the string


for i in str1:

130) What is Pyunit in python

Answer: Pyunit is a python unit test library.  It is coming with python installation itself. we can implement unit test cases for the source code. We can check the output of the function using some simple code

131) explain inheritance in python with example

Answer: Inheritance in python is a way to acquire the properties of one class to another class. Here the inherited class can use the attributes and methods.

Here is the example:

class animal():
def __init__(self,radious=1):
print(‘animal created’)
def eat(self):
print(‘Animal eat’)
class dog(animal):
def __init__(self):
print(‘Dog created’)
def bark(self):
print(‘I am barking’)
d=dog() inherited method

132) What the return key word will do in python functions

Answer: The return key word in python function will return the value to function again. Return will be very use full keyword we can use instead of Global variable.


def add(x,y):
return z

133) Write a program to convert all strings in list to integers


test_list = [‘1’, ‘4’, ‘3’, ‘6’, ‘7’] print (“Original list is : ” + str(test_list))
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
print (“Modified list is : ” + str(test_list))

134) Write a logic to find the max sum of a list in another list


def maximumSum(list1):
maxi = 0
for x in list1:
sum = 0
for y in x:
sum+= y
maxi = max(sum, maxi)
return maxi
list1 = [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] print maximumSum(list1)

135) What is Decorator in python

Answer: A decorator in python can modify the behavior of another function

136) Find Max length of any given sublist


def FindMaxLength(lst):
maxList = max((x) for x in lst)
maxLength = max(len(x) for x in lst )
return maxList, maxLength
lst = [[‘A’], [‘A’, ‘B’], [‘A’, ‘B’, ‘C’]] print(FindMaxLength(lst))

137) Write a program to draw a board ex: 3by3 or 4by4 etc


Size=int(input(‘Enter your board size’))
X=” — ”
Y=”|    ”
for I in range(size):

138) Write a program to check given number is prime using for loop with else


num=int(input(“Enter your number to check”))
for i in range(2,num):
if num%i==0:
print(‘Not a prime’)
print(‘Given is prime’) 

139) How will you reload a module of python, explain

Answer: We have one inbuilt function called reload(),which is taking module as an argument and reloads the module.

140) What is Django explain in your words

Answer: Django is a web framework to develop web application using python. Django it self developed in python. Django uses MVT frame work(Model, View, Template). It is open source and very easy to adapt.

141) Explain the working components of Django

Answer: This python module deals with the data base section of the application. This module is to deal with the expressions for pattern processing. Is the important part of the Django, deals with the logic part.

142) Give me some advantages of Django over using other frameworks

Answer: Django has auto generated admin interface.

143) Talk about sessions in Django

This session helps the user to store the session information. This data is stored in server side.

144) How the Django will work without installing any webserver

Answer: Django comes with one light weight webserver which is running locally and runs the application.

We can start and stop this application using djagno admin commands.

145) What is the Data Bases we can work Django

Answer: We can almost work with any database with Django

Here is some examples : PostgreSQL, MySQL, Oracle, SQLite

But by default Django uses SQLite3

146) How to check the version of Django

Answer: Py -m Django –version