Python Interview Questions and Answers

Home/Uncategorized/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]
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]
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?
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’]
>>> 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?
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]
>>> a[-2]
>>> b = (1,2,3,4)
>>> b[-1]
>>> b[-2]

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?
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’]
>>> 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’]
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?
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
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.?
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?
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?
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?
Java is a static data type,
Python is a dynamic typed-data type.
66) What Does The Ord() Function Do In Python?
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
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__?
1) __repr__() is invoked when you simplified write object’s name on interactive python console and press enter.
2) __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?

  1. sorted([(value,key) for (key,value) in mydict.items()])
  2. 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
By | 2018-12-10T15:11:19+00:00 December 8th, 2018|Categories: Uncategorized|0 Comments

About the Author:

Leave A Comment