Python
Python
class A():
def disp(self):
print("A disp()")
class B(A):
pass
obj = B()
obj.disp()
Answer: d
class A():
pass
class B():
pass
class C(A,B):
pass
a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance
Answer: b
class A:
def one(self):
return self.two()
def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj1=A()
obj2=B()
print(obj1.two(),obj2.two())
a) A A
b) A B
c) B B
d) An exception is thrown
Answer: b
class A:
def __init__(self):
self.__i = 1
self.j = 5
def display(self):
print(self.__i, self.j)
class B(A):
def __init__(self):
super().__init__()
self.__i = 2
self.j = 7
c = B()
c.display()
a) 2 7
b) 1 5
c) 1 7
d) 2 5
Answer: c
Answer: d
a) 1
b) 0
c) None
d) Error
Answer: d
class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()
a) test of B called
test of C called
test of A called
b) test of C called
test of B called
c) test of B called
test of C called
d) Error, all the three classes from which D derives has same method test()
Answer: a
Q11. The assignment of more than one function to a particular operator is _______
a) Operator over-assignment
b) Operator overriding
c) Operator overloading
d) Operator instance
Answer: c
Answer: b
Answer: a
class stud:
'Base class for all students'
def __init__(self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
print(stud.__doc__)
a) Exception is thrown
b) __main__
c) Nothing is displayed
d) Base class for all students
Answer: d
Q 15. What does print(Test.__name__) display (assuming Test is the name of the class)?
a) ()
b) Exception is thrown
c) Test
d) __main__
Answer: c
Answer: a
x=12
def f1(a,b=x):
print(a,b)
x=15
f1(4)
a) Error
b) 12 4
c) 4 12
d) 4 15
Answer: c
def f1(a,b=[]):
b.append(a)
return b
print(f1(2,[3,4]))
a) [3,2,4]
b) [2,3,4]
c) Error
d) [3,4,2]
Answer: d
Answer: c
Q 20: What will be the output of the following Python code?
x=5
def f1():
global x
x=4
def f2(a,b):
global x
return a+b+x
f1()
total = f2(1,2)
print(total)
a) Error
b) 7
c) 8
d) 15
Answer: b
x=100
def f1():
global x
x=90
def f2():
global x
x=80
print(x)
a) 100
b) 90
c) 80
d) Error
Answer: a
Q 22) Read the following Python code carefully and point out the global variables?
y, z = 1, 2
def f():
global x
x = y+z
a) x
b) y and z
c) x, y and z
d) Neither x, nor y, nor z
Answer: c
class Demo:
def __init__(self,x,y,z):
self.a=x
self._b=y
self.__c=z
a) a
b) __c
c) _b
d) x
Answer: b
class fruits:
def __init__(self):
self.price = 100
self.__bags = 5
def display(self):
print(self.__bags)
obj=fruits()
obj.display()
a) The program has an error because display() is trying to print a private class member
b) The program runs fine but nothing is printed
c) The program runs fine and 5 is printed
d) The program has an error because display() can’t be accessed
Answer: c
class student:
def __init__(self):
self.marks = 97
self.__cgpa = 8.7
def display(self):
print(self.marks)
obj=student()
print(obj._student__cgpa)
a) The program runs fine and 8.7 is printed
b) Error because private class members can’t be accessed
c) Error because the proper syntax for name mangling hasn’t been implemented
d) The program runs fine but nothing is printed
Answer: a
Q1: What is output of following code −
a = (1, 2)
a[0] +=1
A - (1,1,2)
B - 2
C - Type Error
D - Syntax Error
Answer : C
C - True if the elements in A when compared are less than the elements in B.
Answer : B
Ans: C
(A) a
(B) b
(C) c
(D) d
Ans B
Q8: What is the output of following code?
class test:
def __init__(self):
print ("Hello World")
def __init__(self):
print ("Bye World")
obj=test()
(A) Hello World
(B) Compilation Error
(C) Bye World
(D) Ambiguity
Ans: C
Q10: Is it possible to use round function without any argument like round()
(A) Yes
(B) No
Ans:: B
acc = Acc(111)
print (acc.id)
A)111
B)555
C)222
D)111555
Ans: A
def addToCounter(country):
if country in counter:
counter[country] += 1
else:
counter[country] = 1
addToCounter('China')
addToCounter('Japan')
addToCounter('china')
print (len(counter))
A)3
B)2
C)1
D)0
Ans 3
def doThis():
global count
doThis()
print (count)
A)4
B)3
C)2
D)0
ANS: A
Q 15:
dictionary = {1:'1', 2:'2', 3:'3'}
del dictionary[1]
dictionary[1] = '10'
del dictionary[2]
print (len(dictionary))
A)4
B)3
C)2
D)0
ANS: C
class A:
def __init__(self):
self.__i = 1
self.j = 5
def display(self):
print(self.__i, self.j)
class B(A):
def __init__(self):
super().__init__()
self.__i = 2
self.j = 7
c = B()
c.display()
a) 2 7
b) 1 5
c) 1 7
d) 2 5
ANS:C
a) Single-level
b) Double-level
c) Multiple
d) Multi-level
Ans:b
class A:
def __init__(self):
self.__x = 1
class B(A):
def display(self):
print(self.__x)
def main():
obj = B()
obj.display()
main()
a) 1
b) 0
c) 1 0
d) Error
Ans: d
class A:
def __init__(self,x=3):
self._x = x
class B(A):
def __init__(self):
super().__init__(5)
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main()
a) 5
b) 3
c) Error, class member x has two values
d) Error, protected class member can’t be accessed in a subclass
Ans: a
class A:
def __str__(self):
return '1'
class B(A):
def __init__(self):
super().__init__()
class C(B):
def __init__(self):
super().__init__()
def main():
obj1 = B()
obj2 = A()
obj3 = C()
print(obj1, obj2,obj3)
main()
a) 1 1 1
b) 1 2 3
c) ‘1’ ‘1’ ‘1’
d) An exception is thrown
Ans:a
Q 24:A class in which one or more methods are only implemented to raise an
exception is called an abstract class. True or False?
a) True
b) False
Ans: b
f.close()
A. Entire contents of the file are displayed
B. Only two lines of the file are displayed
C. Only 3 lines of the file are displayed
D. Error
Answer: A
------------------------------------------
2. What Will Be The Output Of The Following Code Snippet?
fo = open("myfile.txt", "r") # there is a file myfile.txt
fo.seek(10)
print ("Contents: ", fo.read())
fo.close()
A. first 10 characters of the file are skipped and rest are displayed
B. first 10 characters are displayed
C. first 10 lines are skipped
D. Syntax Error
Answer: A
---------------------------------------------------
3. What Will Be The Output Of The Following Code Snippet?
fo = open("myfile.txt", "w")
fo.writelines(12460)
fo.close()
A. TypeError
B. myfile.txt now contains "12460"
C. myfile.txt now contains 12460
D. gives warning and writes the content
Answer. A
----------------------------------------------
4. What Will Be The Output Of The Following Code Snippet?
with open("hello.txt", "w") as f:
f.write("Hello World how are you today")
A. Runtime Error
B. Hello World how are you today
C. returns a list of one character on each line
D. Hello
Answer: C
------------------------------------------
5. What Will Be The Output Of The Following Code Snippet?
f = open("data.txt", "w")
txt = "This is 1st line\n"
f.writelines(txt, list)
f.seek(0,0)
line = f.readlines()
print ("Read Line: %s" % (line))
f.close()
from the list, if we have to get the strings starting with "astro", which one is
the right way to use?
A. for i in list1:
if re.match("(astro)", i):
print (i)
B. for i in list1:
if re.findall("^(astro)", i):
print (i)
C. print (re.findall("^(astro)", list1))
D. Both A and B
Answer: D
----------------------------------------------------
9. What will be the output of the following Python code?
import re
sentence = 'we are humans and we are just humans'
matched = re.search('(.*(humans))', sentence)
print(matched.group())
A. horses
B. horses are fast
C. 'horses are fast'
D. will print nothing
Answer: D
-------------------------------------------------------
15. What is the output of the line of code shown below?
import re
string = "AABCB!@#$1234"
matched = re.search("\W+", string)
print (matched.group())
A. AABCB
B. 1234
C. AABCB1234
D. !@#$
Answer: D
-------------------------------------------------------
16. Which regular expression will match the string "JUL-28-87":
A. [A-Z]+.[0-9]+.[0-9]+
B. ([A-Z]+)-([0-9]+)-([0-9]+)
C. \w+\-\d+-\d+
D. All of the above
Answer: D
------------------------------------------------------------
17. What will be the output of the following code?
string = "This is python test"
string.replace("python", "perl")
print (string)
A. 87654321
B. 12345678
C. NameError
D. TypeError
Answer: A
--------------------------------------------------------------
23. What will be the output?
print (('hello' + 'world') + ('how are you?') * 0)
A. Error
B. prints nothing
C. helloworld
D. 0
Answer: C
----------------------------------------------------
24. What will be printed from the following code?
string = "PYTHON TEST"
for i in string:
if i == "N":
pass
print (i, end = "")
A. PYTHO TEST
B. PYTHON TEST
C. PYTHONTEST
D. Error
Answer: B
------------------------------------------------------
25. What will the output of the following line?
>>>"PYTHON TEST"[-11:-1:-1]
A. >>>'TSET NOHTY'
B.>>> 'PYTHON TES'
C.>>> PYTHON TEST
D.None of the above
Answer: D
Q1.What is the output of following code?
def add(data):
return data+2
def prod(data):
return data*2
def main_fun(function1,function2, number_list):
result_sum=0
for num in number_list:
if(num%3==0):
result_sum=result_sum+function1(num)
else:
result_sum=result_sum+function2(num)
return result_sum
number_list=[1,3,5,6]
print(main_fun(add, prod, number_list))
a)25
b)15
c)28
Ans a
a)
Index Error
In finally block
b)
Index Error
c)
In finally block
d)
0
In finally block
Ans a
a)28
b)231
c)232
d)None of the above
Ans a
Q8.Which of the following can help us to find the version of python that we are
currently working on?
a) sys.version
b) sys.version()
c) sys.version(0)
d) sys.version(1)
Answer: a
Answer: b
Q10. What will be the output of the following Python code, if the code is run on
Windows operating system?
import sys
if sys.platform[:2]== 'wi':
print("Hello")
a) Error
b) Hello
c) No output
d) Junk value
Answer: b
a)''
b)Error
c)" "
d)None of the above
Ans d
Q15. To include the use of functions which are present in the random library, we
must use the option:
a) import random
b) random.h
c) import.random
d) random.random
Answer: a
a) True
b) False
Answer: a
a) Error
b) Either 10.4, 56.99 or 76
c) Any number other than 10.4, 56.99 and 76
d) 56.99 only
Answer: b
a) sun
b) u
c) either s, u or n
d) error
Answer: c
class EmployeeData:
def __init__(self, sal=0, age=0):
self.sal = sal
self.age = age
def getData(self):
print("{0}+{1}j".format(self.sal,self.age))
empdata = EmployeeData()
empdata.getData()
a)Shows no data
b)0+0j
c)Shows error
d)None of the above
Ans b
obj=Computers(30000)
obj.quantity=12
obj.keyboard=10
print(obj.quantity+len(obj.__dict__))
a)15
b)2
c)22
d)None of the above
Ans a
Ans a
Ans a
Ans a
Q1. Go through the below code and predict the output:
num1=100
num2=0
try:
result=num1/num2
print(result)
except ZeroDivisionError:
print("Zero Division Error Occurred")
a) 100
b) 0
c) Zero Division Error Occurred
d) None of Above mentioned
Answer: c
-------------------------------------------
Q2. What will be the output of the code given below?
def division(a,b):
try:
return int(a)/b
except TypeError:
print("Type error")
except ValueError:
print("Value error")
finally:
print("Finally")
print("Done")
division('A',10)
a) Value error
Finally
Done
b) Type error
Finally
Done
c) Type error
Finally
d) Value error
Finally
Answer: a
-----------------------------------------
Q3.What will be the output of the below code?
def find_sum(a,b):
try:
print(a+c)
except NameError:
print("Function name error")
finally:
print("Sum finally")
try:
find_sum(12,13)
except NameError:
print("Invocation name error")
finally:
print("Invocation finally")
a) Function name error
Answer: c
-----------------------------
Q4. What is the output of the following code snippet?
def fun(number):
if(number<2):
return 1
elif(number/2==2):
return fun(number-1)
else:
return (number-1)*fun(number-1)
print(fun(7))
b) 240
c) 480
d) 60
Answer: b
-------------------------------------
Q5. What is the output of the following code snippet?
import math
num1=234.01
num2=6
num3=-27.01
Answer a
----------------------------------------------------
Q6. What is the output of the below code?
song="JINGLE Bells jingle Bells Jingle All The Way"
song.upper()
song_words=song.split()
count=0
for word in song_words:
if(word.startswith("jingle")):
count=count+1
print(count)
a) 0
b) 3
c) 2
d) 1
Answer: d
-----------------------------------------------------
Q7.What is the output of the following code snippet?
import math
num_list=[100.5,30.465,-1.22,20.15]
num_list.insert(1, -100.5)
num_list.pop(0)
num_list.sort()
print(math.ceil(math.fabs(num_list[0])))
a) 101
b) 100
c) 30
d) 31
Answer: a
-------------------------------------------------
Q8.What is the output of the following code snippet?
sample_dict={'a':1,'b':2}
sample_dict.update({'b':5, 'c':10 })
print(sample_dict.get('a'),sample_dict.get('b'),sample_dict.get('c'))
a) None 5 10
b) 1 5 10
c) 1 2 None
d) 1 5 None
Answer: b
------------------------------------------------------
Q9. The magic methods are recognized by presence of which character?
a) $
b) *
c) &
d) __
Answer: d
--------------------------------------------------------------
Q10.The object type is determined by which method?
a) belongs
b) typeof
c) value
d) type
Answer: d
-----------------------------------------------------
Q11. What is the output of the following programe?
class A:
def __init__(self,X):
self.X = X
def count(self,X):
self.x = self.X + 1
class B(A):
def __init__(self,Y = 0):
A.__init__(self, 3)
self.Y = Y
def count(self):
self.Y += 1
def main():
obj = B()
obj.count()
print(obj.X, obj.Y)
main()
a) An exception is thrown
b) 0 1
c) 3 1
d) 3 0
Answer: c
-----------------------------------------------------
Q12. What is the output of the following programe?
class A:
def __init__(self,X = 3):
self.X = X
class B(A):
def __init__(self):
super().__init__(5)
def display(self):
print(self.X)
def main():
obj = B()
obj.display()
main()
a) 5
b) Error, class member X has two values
c) Error, protected class member can't be accessed in a subclass
d) 3
Answer: a
-------------------------------------
Q13. An imported module is stored as:
a) Linked List
b) Byte compiled form
c) Python code file
d) Obfuscated object
Answer: b
------------------------------------------------------
Q14. What is the output of the following code?
class Demo:
def __init__(self):
pass
def test(self):
print(__name__)
obj = Demo()
obj.test()
a) __main__
b) Exception is thrown
c) Demo
d) __name__
Answer: a
-------------------------------------------------------
Q15. What is the output of the following code?
class Stud:
def __init__(self,roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display(self):
print("Roll no :",self.roll_no,",Grade:",self.grade)
stud1 = Stud(34,'S')
stud1.age = 7
print(hasattr(stud1, 'age'))
a) 7
b) False
c) True
d) Error, as age is not defined
Answer: c
------------------------------------------------
Q16. What is the output of the following code?
class A:
def test1(self):
print("test of A is called")
class B(A):
def test(self):
print("test of B is called");
class C(A):
def test(self):
print("test of C is called");
class D(B,C):
def test2(self):
print("test of D is called");
obj = D()
obj.test()
a) test of B is called
b) test of B is called
test of C is called
c) test of C is called
test of B is called
d) Error, both classes from which D is derived has the same method test()
Answer: a
-------------------------------------------------
Q17. Reloading a module when it has already been imported is done by using which
function?
a) revise
b) reload
c) refresh
d) clean
Answer: c
----------------------------------------------
Q18. A module imported (using an variant) by import statement, does not imports
Answer: a
-----------------------------------------
Q19. You are writing an application that uses the sqrt function. The programe must
Answer: b
------------------------------------------
Q20. You are creating a Python programe that shows a congratulations message
to employee on their service anniversary.
You need to calculate the number of years of service and print a
congratulatory
message.
You have written the following code. Line numbers are included for reference
only.
Answer: c
--------------------------------------------
Q21. Predict the output of this programe
import datetime
d = datetime.datetime(2020,4,7)
print('{:%B-%d-%y}'.format(d))
num = 1234567.890
print('{:,.4f}'.format(num))
a) 2020-April-07
1,234,567.890
b) April-07-20
1,234,567.8900
c) Apr-07-2020
1,234,567.8900
d) Error
Answer: b
-------------------------------------------
Q22. You need to write code that generate a random float with a minimum value of
0.0 and a maximumvalue of 1.0.
Which statement should you use?
a) random.randrange(0.0, 1.0)
b) random.randrange()
c) random.random()
d) random.randint(0,1)
Answer: c
----------------------------------------------
Q23. The output of the following codes are the same.
a) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b) [0, 4, 16, 36, 64]
c) Error
d) No output
Answer:b
-----------------------------------------
Q25.. What will be the output of the following Python code?
Answer: c
1. In file handling, what does the function fileobject.readlines() return?
A. str
B. tuple
C. list
D. none of the above
Answer: C
------------------------------------------
2. In file handling, which is not the method to write a list of strings to a file?
A. fileobj.writelines(iterable)
B. fileobj.write(str) inside a loop
C. fileobj.writelines(str) inside a loop
D. fileobj.write(iterable)
Answer: D
---------------------------------------------------
3. What Will Be The Output Of The Following Code Snippet?
fo = open("myfile.txt", "w")
fo.write(12460)
fo.close()
A. Error
B. writes 12460 to the file
C. writes "12460" to the file
D. writes 1, 2, 4, 6, 0 to the file separately
Answer: A
----------------------------------------------
4. What Will Be The Output Of The Following Code Snippet?
file = open("a.txt", "w")
file.writelines("some string")
file.close()
A. Error
B. writes 'some string' to a.txt
C. writes ["some", "string"] to a.txt
D. None of the above
Answer: B
------------------------------------------
5. When we try to modify an object, a new object is created with modified value.
What is the type of the object?
A. immutable
B. mutable
C. ordered
D. None
Answer: A
-------------------------------------
6. Which of these is not true for dictionaries?
f = open('colors.txt', 'r')
print (f.readlines())
A. red
yellow
blue
B. [�red\n�, �yellow\n�, �blue\n�]
C. ['red', 'yellow', 'blue']
D. Compilation error
Answer: B
-----------------------------------------------------------
8. From the given string, if we want to extract the complete words starting with
'astro', which syntax should be used?
string = "astronaut astrophysics astrology"
A. re.match("(astro.*)", string)
B. re.search("(astro)", string)
C. re.findall("(astro)", string)
D. re.findall("(astro.?*)", string)
Answer: D
----------------------------------------------------
9. What will be the output of the following Python code?
import re
sentence = 'we are humans and we are just humans'
matched = re.findall('\W+', sentence)
print(len(matched))
A. 7
B. 8
C. -1
D. 0
Answer: A
------------------------------------------
10. In regular expression, what is the meaning of the pattern \W?
A. non alpha-numeric
B. alpha-numeric
C. alphabets
D. words
Answer: A
-----------------------------------------------------
11. In regular expression, what is the meaning of the pattern \w?
A. non alpha-numeric
B. alpha-numeric
C. alphabets
D. words
Answer: B
----------------------------------------------
12. Which of the following is true in regular expressions?
A. re.DOTALL
B. re.I
C. re.IGNORECASE
D. None of the above
Answer: A
----------------------------------------------------------------------
14. What will be the output of the following Python code?
import re
sentence = 'horses are fast'
matched = re.search("(\w){5,6}", sentence)
print(matched.group())
A. horses
B. horses are fast
C. 'horses are fast'
D. will print nothing
Answer: A
-------------------------------------------------------
15. What does re.search() return?
A. str
B. object
C. list
D. pattern
Answer: B
-------------------------------------------------------
16. Which regular expression will match the strings "JULY-28-87" and "JUL-28-87":
A. re.findall("[A-Z]{4}.\d+.\d+", strings)
B. re.findall("[A-Z]{3}.\d+.\d+", strings)
C. re.findall("[A-Z]+{3,4}.\d+.\d+", strings)
D. re.findall("[A-Z]{3,4}.\d+.\d+", strings)
Answer: D
------------------------------------------------------------
17. What will be the output of the following code?
string = "This is python test"
print (id(string))
string.replace("python", "perl")
print (id(string))
A. -1
B. 0
C. error
D. 1
Answer: A
---------------------------------------------------------------
20. What is the output of the following code?
string = "This is python"
print (string.rfind("is"))
A. 2
B. 1
C. 5
D. None of the above
Answer: C
----------------------------------------------------
21. What is the output of the following code?
string = "A B C D E F G"
for i in string:
print (ord(i), end = " ")
A. 65 32 66 32 67 32 68 32 69 32 70 32 71
B. Error
C. 65 66 67 68 69 70 71
D. None of the above
Answer: A
----------------------------------------------------------
22. What will be the output of the following code?
string = "12345678"
s = s[::1]
print (s)
A. 87654321
B. 12345678
C. NameError
D. TypeError
Answer: B
--------------------------------------------------------------
23. What will be the output?
inp = "1 2 3 4 5 6".split()
A. [1, 2, 3, 4, 5, 6]
B. prints nothing
C. ['1', '2', '3', '4', '5', '6']
D. 1 2 3 4 5 6
Answer: C
----------------------------------------------------
24. Given a string:
string = "PYTHON TEST"
A. string[string.find(" "):]
B. string[string.find(" ") + 1:]
C. string[" ":]
D. None of the above
Answer: B
------------------------------------------------------
25. What will be the output of the following line?
>>>"PYTHON TEST"[:1:11:1]
A. >>>'TSET NOHTY'
B.>>> 'PYTHON TES'
C.>>> PYTHON TEST
D. Error
Answer: D
Q1. Which of the following statement is true?
A. If the number of elements are known in advance, then it is better to use linked
list rather than array
C. Any element in a linked list can be directly accessed whereas in array it cannot
be accessed directly
ANS: B
A. 5 13 25 16
B. 27 22 41 57
C. 5 22 41 16
D. 5 22 41 57
ANS: C
Q3. What is the output of following function when head node of following linked
list is passed as input?
1->2->3->4->5
def fun(head):
if(head==None):
return
if head.get_next().get_next()!= None:
print(head.get_data()," ", end='')
fun(head.get_next())
print(head.get_data()," ",end='')
A. 1 2 3 4 3 2
B. 1 2 3 4 3 2 1
C. 1 2 3 4
D. 1 2 3 4 4 3 2
ANS: B
Q4. What will be the order of elements in the linked list after line 19?
def fun(prv,nxt,data):
if(nxt==None):
return
if(nxt.get_data()==data):
global sample
sample.add(data)
prv.set_next(nxt.get_next())
return
else:
fun(nxt,nxt.get_next(),data)
sample=LinkedList()
sample.add(10)
sample.add(20)
sample.add(5)
sample.add(55)
sample.add(38)
sample_head=sample.get_head()
fun(sample_head, sample_head,5)
A. 10 20 55 38 5
B. 10 20 55 5 38
C. 10 20 55 38 38
D. 10 20 5 55 38
ANS: A
Q5. What does the below function using the Stack datastructure do?
def fun(n):
stack = Stack(100)
while (n > 0):
stack.push(n%10)
n =int (n/10)
result=0
while (not stack.is_empty()):
result+=stack.pop()
return result
A. Takes a number 'n' as input and returns the sum of its digits
C. Takes a number 'n' as input and returns the sum of all its digits divisible by
10
D. Takes a number 'n' as input and divides each digit of the number by 10 and
returns the sum of result of each division operation
ANS: A
Q6. Open a word editor and type the following. (Save every time a new character is
entered)
(C*D)
Now perform Undo operation (Ctrl + Z) once. What is the resultant expression after
the first Undo operation?
A. (C*D)
B. (C*D
C. (C*
D. All character will be erased
ANS: B
Q7. Open a word editor and type the following. (Save every time a new character is
entered)
(C*D)
A. Queue
B. Array
C. Stack
D. LinkedList
ANS: C
Q8. John, Mathews and Suzanne are team members working on the same project. The
project has one printer which can be shared by all the team members. For a team
meeting the project manager has asked all the three members to prepare a report
individually and carry a print out of the same. Mathews was able to finish the
report first and followed by Suzanne and then John. They gave the print command
based on the order in which they finished.
Whose print request will reach the printer first?
A. John
B. Mathews
C. Suzanne
D. Not Mentioned
ANS: B
Q9. John, Mathews and Suzanne are team members working on the same project. The
project has one printer which can be shared by all the team members. For a team
meeting the project manager has asked all the three members to prepare a report
individually and carry a print out of the same. Mathews was able to finish the
report first and followed by Suzanne and then John. They gave the print command
based on the order in which they finished.
Whose print request will reach the printer last?
A. John
B. Mathews
C. Suzanne
D. Not Mentioned
ANS: A
Q10. John, Mathews and Suzanne are team members working on the same project. The
project has one printer which can be shared by all the team members. For a team
meeting the project manager has asked all the three members to prepare a report
individually and carry a print out of the same. Mathews was able to finish the
report first and followed by Suzanne and then John. They gave the print command
based on the order in which they finished.
Which data structure do you think is used to store the print request?
A. Queue
B. Array
C. Stack
D. LinkedList
ANS: A
Q11. What does the below function using the Queue data structure do?
def fun(n):
aqueue = Queue(100)
for num in range(1, n+1):
aqueue.enqueue(num)
result=1
while (not(aqueue.is_empty())):
num = aqueue.dequeue()
result*=num
print(result)
ANS: A
Q12. What does the below function using the Queue data structure do?
def fun(num):
if(num==0):
return 0
else:
queue.enqueue(num%10)
res=fun(num//10)
res=res*10+queue.dequeue()
return res
queue = Queue(100)
print(fun(123))
A. 123
B. 321
D. 321123
ANS: B
A. 56,32,30,25,23,18,17,15,14,11
B. 11,14,17,23,32,56,15,18,25,30
C. 11,14,15,17,18,23,25,30
D. 11,14,15,17,18,23,25,30,32,56
ANS: D
Q14. A travel agent plans trips for tourists from Chicago to Miami. He gives them
three ways to get from town to town: airplane, bus, train.Once the tourists arrive,
there are two ways to get to the hotel: hotel van or taxi. The cost of each type of
transportation is given in the table below.Which data structure can be used to
represent all the possible ways to go from Chicago to Miami?
Transportation Type Cost
Airplane $ 350
Bus $ 150
Train $ 225
Hotel Van $ 60
Taxi $ 40
A. Tree
B. Graph
C. Queue
D. Stack
ANS: B
Q15. In an ATM, a customer can get a mini statement of his/her last 5 transactions.
Which is the most appropriate data structure to model the mini statement?
A. LIST
B. Queue
C. Stack
D. Graph
ANS: C
Q16. Which is the most appropriate data structure to model the token for cash
withdrawal in a bank? 1st token is provided to the first person who has arrived to
withdraw money. The next person is provided the 2nd token etc. The person who got
the first token will be serviced first.
A. LIST
B. Queue
C. Stack
D. Graph
ANS: B
Q17. Ramya wants to model all the items in a retail store under various categories
and sub-categories. Which of the below data structures can be used to optimally
represent it?
A. TREE
B. Queue
C. Stack
D. Graph
ANS: A
Q18. The following values are to be stored in a hash table (arriving in the order
shown) using the hash function, h(k)= k%5.
81, 20, 34, 42, 21, 45
Assume that the hash values are stored in ascending order. Identify whether
collision will occur while mapping the values using the hash function.
ANS: A
Q19. The following values are to be stored in a hash table: 24, 35, 45, 90, 43.
Which of the below hash-functions is the best?
A. h(k)= k%5
B. h(k)= k%4
C. h(k)= k%3
D. h(k)= k%2
ANS: B
A. 1 2 6 7 9
B. 2 6 1 10 17
C. 2 8 1 9 7
D. 1 10 17 2 6
ANS: B
A. 12 7 5 3 1
B. 29 24 18 12 6
C. 5 7 5 3 1
D. 5 24 18 12 6
ANS: D
A. True
B. False
ANS: A
Q23. Based on the number guessing game, answer the following:
Assume that the numbers in the number guessing game are stored in a list and there
are 30 of them in the list. How many guesses will be required to find a number
stored at index position 24 in the list?
A. 24
B. 25
C. 30
D. 1
ANS: B
Q24. Using this strategy if you have to find 25 from a list containing numbers from
1 to 50 arranged in ascending order, how many guesses do you have to make?
A. 0
B. 1
C. 25
D. 50
ANS: B
Q25. Using this strategy if you have to find 50 from a list containing numbers from
1 to 50 arranged in ascending order, how many guesses do you have to make?
A. 6
B. 8
C. 4
D. 2
ANS: A
Q1: What is setattr() used for?
A. To access the attribute of the object
B. To set an attribute
C. To check if an attribute exists or not
D. To delete an attribute
Answer: Option B
Q2: What are the methods which begin and end with two underscore characters called?
A. Special methods
B. In-built methods
C. User-defined methods
D. Additional methods
Answer: Option A
def f(x):
yield x+1
print("test")
yield x+2
g=f(9)
A. Error
B. test
C. test1012
D. No output
Answer: Option D
int('65.43')
A. ImportError
B. ValueError
C. TypeError
D. NameError
Answer: Option B
Answer: Option D
main()
A. 11
B. 2
C. 1
D. An exception is thrown
Answer: Option B
def f1():
x=100
print(x)
x=+1
f1()
A. Error
B. 100
C. 101
D. 99
Answer: Option B
Answer: Option B
A. * abcdef*
B. * abcdef *
C. *abcdef *
D. * abcdef*
Answer: Option B
Answer: Option C
Q 19: What is the output of the code shown below?
print(not(3>4))
print(not(1&1))
A. True
True
B. True
False
C. False
True
D. False
False
Answer: Option B
i = 2
while True:
if i%3 == 0:
break
print(i,end=" ")
i += 2
A. 2 4 6 8 10 …
B. 2 4
C. 2 3
D. error
Answer: Option B
x = "abcdef"
i = "a"
while i in x:
x = x[:-1]
print(i, end = " ")
A. i i i i i i
B. a a a a a a
C. a a a a a
D. none of the mentioned
Answer: Option B
x = "abcdef"
i = "i"
while i in x:
print(i, end=" ")
A. no output
B. i i i i i i …
C. a b c d e f
D. abcdef
Answer: Option A
x = 'abcd'
for i in x:
print(i.upper(),end=" ")
A. a b c d
B. A B C D
C. a B C D
D. error
Answer: Option B
A. 0 1 2
B. a b c
C. 0 a 1 b 2 c
D. none of the mentioned
Answer: Option B
a = [0, 1, 2, 3]
for a[0] in a:
print(a[0],end=" ")
A. 0 1 2 3
B. 0 1 2 2
C. 3 3 3 3
D. error
Answer: Option A
Q1
When the values of a=7, b=6 and c=3, which among the following
logical expressions would be FALSE?
c) (a*c)>(a*b*c) or (a*c)<=(b*c)
Answer: c
------------------------------------------------
Q2
What would be the output of the below Python code?
list1 = [10,20,0,40,0]
def test():
try:
i=3
if(list1[i]/list1[i+1]>1):
value=i+1
except ZeroDivisionError:
print("1")
except IndexError:
print("2")
finally:
print("4")
print("5")
test()
a) 1
5
b) 1
4
5
c) 2
4
5
d) 1
4
Answer:b
-------------------------------------
Q3
Consider the marks list given below.
a) report=report[:1]+marks[5:]
b) report=marks[2:3]+marks[-2:]
c) report=marks[-4:-2]
d) report=report[:2]
Answer: a
------------------------------
Q4
What would be the output of following Python code?
name1 = "Roger"
name2 = "Robert"
def swap_name(name1,name2):
temp = name1
name1 = name2
name2 = temp
print("Before swapping: name1="+name1+" name2="+name2)
swap_name(name1, name2)
print("After swapping: name1="+name1+" name2="+name2)
Answer:c
-------------------------------------------------
Q5
What will be the output of the following Python code?
import datetime
d=datetime.date(2020,02,10)
print(d)
a) Error
b) 2020-02-10
c) 10-02-2020
d) 02-10-2020
Answer:a
----------------------------------------------
Q6
What is the output of the below Python code?
Note:Assume that necessary imports have been done
temp = ['Mysore','Bangalore','Pune','Chennai']
temp.sort()
count1 = len(temp[0])
count2 = len(temp[-1])
final_var = math.ceil(count1/count2)
print(final_var)
a) 3
b) 2
c) 1
d) 4
Answer:a
------------------------------
Q7 of 25
What would be the output of the below Python code?
import re
temp = "indiparker@ind.com"
temp1 = ''
if(re.search(r'@ind\.',temp)):
temp1 = re.sub(r'i\w+(\.com)',r'edu\1',temp)
print(temp1)
a) eduparker@edu.com
b) indiparker@edu.com
c) eduparker@ind.com
d) The code will not result in any output as there is no match
Answer: b
---------------------------------------
Q8
What would be the output of the below Python code?
f = lambda x: (x*2)%3!=0
def pick(f, list1):
for item in list1:
if(not f(item)):
list1.remove(item)
list=[1,2,3,4,5,6,7,8,9]
pick(f,list)
print(list)
a) [3, 6, 9]
b) [1, 2, 4, 5, 7, 8]
c) [2, 4, 6, 8]
d) [1, 3, 5, 7, 9]
Answer:b
------------------------------------------------
Q9
What would be the output of the below Python code?
var = 200
if(var > 200):
print("Within first block")
if(var == 150):
print("which is 150")
elif(var == 100):
print("Which is 100")
elif(var > 50):
print("Within second block")
if(var%5 == 0):
print("Which is multiple of 5")
elif(var%10==0):
print("Which is multiple of 10")
else:
print("Neither multiple of 5 nor multiple of 10")
else:
print("Could not find true expression")
print("Good bye!")
Answer:a
-----------------------------------------
Q10
What does the below Python code do?
for i in range(1,6):
for j in range(1,6):
if(i%j!=0):
pass
elif(j<i):
continue
else:
print(i*j)
Answer:b
---------------------------------------------
Q11
What will be the output of the below Python code?
num1 = 11//10
num2 = 11%10
num3 = 20
num4 = 40
num5 = 5
if(num3>num4):
if(num3>num5):
print(num5*num4/num3)
else:
print(num3/num5)
else:
if(num1==num2):
print(num4/num3)
else:
print(num4/num5)
a) 2.0
b) 4.0
c) 10.0
d) 8.0
Answer: a
---------------------------------------
Q12
What would be the output of the below Python code?
i=0
j=10
while i<=10 and j>1:
print(i, j)
j = j - 1
i = i + 1
if(i==j):
break
a) 0 10
1 9
2 8
3 7
4 6
5 5
b) 1 9
2 8
3 7
4 6
c) 0 10
1 9
2 8
3 7
4 6
d) 1 9
2 8
3 7
4 6
5 5
Answer: c
----------------------------------------
Q13
What is the output of the below Python code?
a) HELLO?
b) HELLO
c) fine
d) Hello? how are u?
Answer: b
-------------------------------------
Q14
What is the output of the below Python code?
a) Count : 2
mack AND mill went up THE hill
b) Count : 3
Mack and Mill went up the Hill
c) Count : 3
MACK and MILL WENT UP the HILL
d) Count : 1
mack and mill went up the hill
Answer: a
------------------------------------------------
Q15
Consider the below Python code:
def fun(n):
if n < 1:
return 0
elif n%2 == 0:
return fun(n-1)
else:
return n + fun(n-2)
a) fun(11)
b) fun(12)
c) fun(9)
d) fun(13)
Answer: c
--------------------------------------------
Q16
Identify the Python code to be written in lines Line 1, Line 2 and Line 3 so as to
get the below output.
Emp id : 100
Emp id : 101
Emp Count 2
class Employee:
__count = 100
def __init__(self,name):
self.name = name
#Line 1
#Line 2
@staticmethod
def totalcount():
#Line 3
emp1 = Employee("Jack")
print("Emp id :",emp1.id)
emp2 = Employee("Tom")
print("Emp id :",emp2.id)
Employee.totalcount()
a) Line1: Employee.__count=100
Line2: self.id=Employee.__count+1
Line3: print("Emp Count",Employee.__count-100)
b) Line1: self.id=Employee.__count
Line2: Employee.__count+=1
Line3: print("Emp Count",Employee.__count-100)
c) Line1: self.id=100
Line2: Employee.__count+=1
Line3: print("Emp Count",Employee.__count)
d) Line1: self.id=Employee.__count+1
Line2: Employee.__count+=1
Line3: print("Emp Count",Employee.__count)
Answer: b
-----------------------------------------------------------
Q17
class Base:
def __init__(self):
self.__value = 200
def get_value(self):
return self.__value+1
class Child(Base):
def get_num(self):
num = 100
return num
class GrandChild(Child):
def __init__(self):
self.num = 200
child = Child()
grandchild = GrandChild()
print(grandchild.get_value())
What changes should be done in the above code so as to get the output as 201?
Answer:c
------------------------------------------------------------------
Q18
Consider the Python code given below.
class ClassA:
def __init__(self):
self.__var_one = 100
def method_one(self):
return self.__var_one
class ClassB(ClassA):
def __init__(self,var_two):
#Line 1__________
self.__var_two = var_two
def method_two(self):
final_val = self.__var_two + self.method_one() #Line 2
return final_val
bobj = ClassB(50)
print(bobj.method_two())
What changes should be done in the above code so as to get the output as 150?
Note: Line numbers are for reference only
Answer: a
----------------------------------
Q19.
What will be the output of the Python code given below?
class ExceptionOne(Exception):
pass
class Test:
counter = 1
@staticmethod
def perform_test(temp_list, n):
try:
if(temp_list[n]>=5):
Test.counter += 1
temp_list[n] -= 2
raise ExceptionOne()
temp_list[n] = 5
else:
raise Exception()
except Exception:
Test.counter -= 5
except ExceptionOne:
Test.counter += 5
print("Data:",temp_list[n])
try:
t = Test()
t.perform_test([2,4,7,5,1],3)
finally:
print("Counter:",Test.counter)
a) Data: 3
Counter: -3
b) Data: 3
Counter: 7
c) Counter: -3
d) Data: 3
Answer: a
----------------------------------------------
Q20
class Alpha:
def one(self):
return 10
def two(self):
return self.one()
class Beta(Alpha):
def one(self):
return 10
def three(self):
return 10
class Gamma(Beta):
def one(self):
return 10
def four(self):
return self.one()
def three(self):
return self.two()
def five(self):
return 10
gobj = Gamma()
num1 = gobj.two() + gobj.three() + gobj.four()
num2 = gobj.three() + gobj.four() + gobj.one()
num3 = gobj.one() + gobj.two() + gobj.three()
a) Only iv)
b) Both ii) and iii)
c) Only i)
d) Only ii)
Answer: c
----------------------------------------------------
Q21
Consider the Python code given below.
class ClassAA:
def method1(self):
return 10
def method2(self):
return 20
class ClassBB:
def method3(self):
return 60
def method4(self):
return 70
class ClassCC(ClassAA):
def method1(self):
return 30
def method4(self):
return 40
class ClassDD(ClassBB):
def method1(self):
return 50
def method2(self):
return 60
obj1 = ClassCC()
obj2 = ClassDD()
1. print(obj1.method2()+obj2.method4()) A. 100
2. print(obj1.method1()+obj2.method1()) B. 80
3. print(obj1.method4()+obj2.method3()) C. 90
Answer: a
---------------------------------------------------------
Q22
import datetime
x = datetime.datetime(2018, 2, 1)
print(x.strftime("%B"))
a) Feb
b) February
c) Jan
d) January
Answer: b
--------------------------------------------------
Q23
To convert a date which is in string format back to date format,
which function do we use ?
a) now()
b) strftime()
c) strptime()
d) strdatetime()
Answer: c
-----------------------------------------------
Q24
What will be the output of the following Python code if the system date is 18th
June, 2019 (Tuesday)?
import datetime
tday=datetime.date.today()
print(tday)
a) 18-06-2019
b) 06-18-2019
c) 2019-06-18
d) Error
Answer: c
-------------------------------------------------
Q25
What will be the output of the following Python code if the system date is 13th
February, 2020 (Thursday)?
import datetime
tday=datetime.date.today()
print(tday.isoweekday())
a) Thu
b) Thursday
c) 4
d) 5
Answer: c
Q1. What is the output of following code?
print(type(type()))
a)Error
b)Null
c)None
Answer a
print(type(type))
a) <class 'type'>
b)Error
c)<class ‘None’>
Answer a
class cc:
def f1(self,a,b):
self.a=a
self.b=b
return self.a+self.b
o=new cc()
print(o.f1(4,4))
a)8
b)Error
c)4
list1=[None]*3
print(list1)
b)[ ]
Answer a
for i in string:
a)my name is x
b) m, y, , n, a, m, e, , i, s, , x,
Answer b
print(list(filter(bool, l)))
b)Error
c)[ ]
Answer a
Q7.What is the output of following code?
print([] or {})
a) {}
b)[]
c)True
d)False
Answer a
class Truth:
pass
x=Truth()
print(bool(x))
a)None
b)Error
c) True
Ans c
Q9.
print("-%5d0",989)
a) -%5d0 989
b)Error
c)-09890
d)98900
Ans a
Answer: d
print(~~5)
a)5
b)-6
c)101
Answer a
Q13.
list1=[]
list1[0]=100
print(list1)
a)100
b)[100]
c)Error
Answer c
class c1:
@classmethod
def m1(cls):
print("hello")
ob=c1()
ob.m1()
a)hello
b)Address of object ob
c)Error
Answer a
class myclass:
@staticmethod
def m1():
print("hello")
ob=myclass()
ob.m1()
a)hello
b)error
c)Address of ob object
Answer a
class class1:
def __init__(self,a,b,c):
self.a=a
self._b=b
self.__c=c
class class2:
pass
o=class1(1,2,3)
print(self.a)
a)Error
b)1
c)2
Answer a
class class1:
def __init__():
print("class1's __init__")
class class2(class1):
def __init__():
print("class2's __init__")
ob=class2()
a) class1's __init__
b)Error
c) class2's __init__
Answer b
def __init__(me,a):
me.a=a
print(a)
ob=class1(10)
a)10
b)Error
Answer a
a=1,2,3,4
print(a)
a) (1, 2, 3, 4)
b)1
c)4
d)Error
Answer a
20. What is the output of following code?
x=2
y=x<<2
y=~y+1
print(y)
a)4
b)-4
c)-8
d)None of the above
Answer c
a, b = c = 2 + 2, ''Hello''
a) a=4, 'Hello'
b= 4, 'Hello'
c= 4, 'Hello'
b) a=2
b= 'Hello'
c=4, 'Hello'
c) a=4
b= 'Hello'
c=4, 'Hello'
d) a=4
b= 'Hello'
c= NULL.
Answer: c
d) error
Answer: d
Q 3 - Find the output of the code?
class test:
def __init__(self):
print("Hello World")
def __init__(self):
print ("Bye World")
obj=test()
(A) Hello World
(B) Compilation Error
(C) Bye World
(D) Ambiguity
Answer: C
a) 2 3 -4 3
b) 2 3 -3 3.12
c) 2 4 -3 3
d) 2 3 -4 3.12
Answer: B
class change:
def __init__(self, x, y, z):
self.a= x - y * z
x =change(1,2,3)
y =getattr(x,'a')
setattr(x,'a', y)
print(x.a)
a)6
b)-5
c)Error
d) 0
Answer: B
print(type(print("hello")))
a) Null
b) <class int>
c) <class str>
d) None of the above
Answer: d
a) IS A Relationship
b) HAS A Relationship
c) USES Relationship
d)None of the above.
Answer: a
a) Polymorphism
b) Inheritance
c) Encapsulation
d) None of the above
Answer: b
main()
a) 11
b) 2
c) 1
d) An exception is thrown
Answer: b
class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()
a) test of B called
test of C called
b) test of C called
test of B called
c) test of B called
test of C called
test of A called
d) Error, all the three classes from which D derives has same method test()
Answer: c
class Derived_Test(Test):
def __init__(self):
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y)
main()
a) 01
b) 00
c) Error
d) 10
Answer: c
elements=0,1,2
def incr(x):
return x+1
print(list(map(incr,elements)))
a)[1,2,3]
b)[0,1,2]
c)error
d) none of the mentioned
Answer: a
a) {1, 2, 3, 4}
b) {1, 2, 3}
c) Invalid Syntax
d) None
Answer: d
a) 0
b) 1
c) 2
d) This code will raise a runtime error
Answer: a
print(2**2**3**1+5)
a) 12
b) 64
c) 261
d) This code will raise a runtime error
Ans c
Q 19 - What is the output of the following code?
val = 154
while(not(val)):
val **=2
else:
val//=2
print(val)
a) 77
b) 154
c) 11858
d) 23716
e) None of above
Answer: a
print("***"*0)
a)3
b)0
Ans b
Ans b
>>> True==””
a)False
b)True
Ans a
Ans d
>>> True==()or[]
a)None
b)False
c)True
d)[ ]
Ans d
count={}
count[(1,2,4)] = 5
count[(4,2,1)] = 7
count[(1,2)] = 6
count[(4,2,1)] = 2
tot = 0
for i in count:
tot=tot+count[i]
print(len(count)+tot)
a) 25
b) 17
c) 16
d) Tuples can’t be made keys of a dictionary
Answer: c
a={}
a[2]=1
a[1]=[2,3,4]
print(a[1][1])
a) [2,3,4]
b) 3
c) 2
d) An exception is thrown
Answer: b
Answer: c
65. What will be the output of the following Python code snippet?
total={}
def insert(items):
if items in total:
total[items] +=1
else:
total[items]=1
insert('Apple')
insert('Ball')
insert('Apple')
print(len(total))
a) 3
b) 1
c) 2
d) 0
Answer: c
66. What will be the output of the following Python code snippet?
a ={}
a[1]=1
a['1']=2
a[1]=a[1]+1
count =0
foriin a:
count += a[i]
print(count)
a) 1
b) 2
c) 4
d) Error, the keys can’t be a mixture of letters and numbers
Answer: c
67. What will be the output of the following Python code snippet?
numbers ={}
letters ={}
comb ={}
numbers[1]=56
numbers[3]=7
letters[4]='B'
comb['Numbers']= numbers
comb['Letters']= letters
print(comb)
Answer: d
69. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
fori,jina.items():
print(i,j,end=" ")
a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”
Answer: a
70. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method
Answer: b
a={1:"A",2:"B",3:"C"}
print(a.get(5,4))
Answer: d
73. The character Dot (that is, ‘.’) in the default mode, matches any character other than
_____________
a) caret
b) ampersand
c) percentage symbol
d) newline
Answer: d
74. The expression a{5} will match _____________ characters with the previous regular
expression.
a) 5 or less
b) exactly 5
c) 5 or more
d) exactly 4
Answer: b
a) ‘^’, ‘$’
b) ‘$’, ‘^’
c) ‘$’, ‘?’
d) ‘?’, ‘^’
Answer: a
L1 = list()
L1.append([1, [2, 3], 4])
L1.extend([7, 8, 9])
print(L1[0][1][1] + L1[2])
T = tuple('jeeps')
a, b, c, d, e = T
b = c = '*'
T = (a, b, c, d, e)
print(T)
a) (‘j’, ‘*’, ‘*’, ‘p’, ‘s’)
b) (‘j’, ‘e’, ‘e’, ‘p’, ‘s’)
c) (‘jeeps’, ‘*’, ‘*’)
d) KeyError
Ans. (a)
80. What is the value of L at the end of execution of the following program?
L = [2e-04, 'a', False, 87]
T = (6.22, 'boy', True, 554)
fori in range(len(L)):
if L[i]:
L[i] = L[i] + T[i]
else:
T[i] = L[i] + T[i]
break
a) [6.222e-04, ‘aboy’, True, 641]
b) [6.2202, ‘aboy’, 1, 641]
c) [6.2202, ‘aboy’, True, 87]
d) [6.2202, ‘aboy’, False, 87]
Ans. (d)
f = None
if i > 2:
break
print(f.closed)
A. True
B. False
C. None
D. Error
Answer: A
------------------------------------------
fo = open("myfile.txt", "w+")
seq="TechBeamers\nHello Viewers!!"
fo.writelines(seq )
fo.seek(0,0)
print (line)
fo.close()
A. TechBeamers
Hello viewers!!
TechBeamers
Hello Viewers!!
D. Syntax Error
Answer: B
---------------------------------------------------
fo = open("myfile.txt", "w+")
fo.writelines( txt )
fo.seek(0, 2)
fo.writelines( seq )
fo.seek(0,0)
line = fo.readlines()
fo.close()
Read Line: [‘This is 1st line, This is 2nd line, This is 3rd line’]
D. Runtime Error
Answer. A
----------------------------------------------
data = f.readlines()
words = line.split()
print (words)
f.close()
A. Runtime Error
D. Hello
Answer: C
------------------------------------------
f = open("data.txt", "r")
f.writelines( txt )
f.seek(0,0)
line = f.readlines()
f.close()
B. []
C. IO Error
D. None
Answer: C
-------------------------------------
f = open("testfile", "r")
except IOError:
else:
D. IO Error
Answer: B
----------------------------------------------
f = open('colors.txt', 'w')
f.writelines(colors)
f.close()
f.seek(0,0)
for line in f:
print (line)
A. red
yellow
blue
D. Compilation error
Answer: C
-----------------------------------------------------------
import re
sum = 0
pattern = 'back'
if re.match(pattern, 'backup.txt'):
sum += 1
if re.match(pattern, 'text.back'):
sum += 2
if re.search(pattern, 'backup.txt'):
sum += 4
if re.search(pattern, 'text.back'):
sum += 8
print(sum)
A. 3
B. 7
C. 13
D. 14
Answer: C
----------------------------------------------------
import re
print(matched.groups())
C. ('we', 'humans')
Answer: A
------------------------------------------
import re
print(matched.group())
C. ('we', 'humans')
D. we are humans
Answer: D
-----------------------------------------------------
import re
print(matched.group(2))
A. are
B. 'we'
C. 'humans'
Answer: A
----------------------------------------------
import re
print(matched.groupdict())
D. 'are'
Answer: A
-------------------------------------------------------------------
import re
print(matched.groups())
D. 'are'
Answer: B
----------------------------------------------------------------------
import re
print(matched.group(2))
D. are
Answer: D
-------------------------------------------------------
Answer: D
-------------------------------------------------------
A. [a-z]+W[0-9]+W[0-9]+
B. ([a-z]+)W([0-9]+)W([0-9]+)
C. JUL-w-w
D. (.*?)-(\d+)-(\d+)
Answer: D
------------------------------------------------------------
string[8:14] = "Java"
print (string)
Answer: C
----------------------------------------------------------
A. This is a string
B. This is a
string
C. This is a \n string
Answer: C
----------------------------------------------------------------
print ("""This is a
string""")
A. This is a
string
B. This is a string
C. This is a \nstring
D. Both B and C
Answer: A
---------------------------------------------------------------
20. What is the output of the following code?
for i in string:
if i == "i":
print (string.find("i"))
A. 2
B. 2
C. 5
D. Both A and B
Answer: B
----------------------------------------------------
string = "ABCDEFG"
for i in string:
A. 65 66 67 68 69 70 71
B. Error
Answer: B
----------------------------------------------------------
22. What will be the output of the following code?
string = "12345678"
for i in range(len(string)):
string[i] = str(string[i])
print (string)
B. 12345678
C. Error
D. "12345678"
Answer: C
--------------------------------------------------------------
A. Error
C. stringstring
D. string2 string2
Answer: A
----------------------------------------------------
print (string[-1:0:-1])
A. TSET NOHTY
B. No output
C. 'YTHON TEST'
D. Error
Answer: A
------------------------------------------------------
>>>"PYTHON TEST"[-11:-1:1]
A. 'TSET NOHTY'
B. 'PYTHON TES'
C. PYTHON TEST
D. No output
Answer: B
class Vardhan:
def __init__(self, id):
id = 1000
self.id = id
print (id)
val = Vardhan(200)
A. SyntaxError, this program will not run
B. 1000
C. 200
D. None of the above
Correct : Option B
s = "\t\tWelcome\n"
print(s.strip())
A. \t\tWelcome\n
B. Welcome\n
C. \t\tWELCOME
D. Welcome
Correct : Option D
sam = Person(100)
sam.__dict__['age'] = 49
A. 1
B. 2
C. 49
D. 51
Correct : Option D
class B(A):
def __init__(self):
super().__init__()
b = B()
A. The __init__ method of only class B gets invoked.
B. The __init__ method of class A gets invoked and it displays “i from A is 0”.
C. The __init__ method of class A gets invoked and it displays “i from A is 60”.
D. The __init__ method of class A gets invoked and it displays “i from A is 90”.
Correct Option D
Q5:Which Of The Following Statements Can Be Used To Check, Whether An Object “Obj” Is
An Instance Of Class A Or Not?
A. obj.isinstance(A)
B. A.isinstance(obj)
C. isinstance(obj, A)
D. isinstance(A, obj)
Correct Option C
class Test:
def __init__(self, s):
self.s = s
def print(self):
print(self.s)
msg = Test()
msg.print()
A. The program has an error because class Test does not have a constructor.
B. The above code produces an error because the definition of print(s) does not include .
C. It executes successfully but prints nothing.
D. The program has an error because of the constructor call is made without an argument
Correct : Option D
def getY(self):
return self.__y
val= Test()
val.__y = 45
print(val.getY())A. The program has an error because y is private and should not access it from
outside the class.
B. The program has an error because you cannot name a variable using __y.
C. The code runs fine and prints 1.
D. The code executes successfully and prints 45.
Answer. C
class Counter:
def __init__(self):
self.counter = 0
main()
A. counter is 101 , number of times is 0
B. Error
C. counter is 100, number of times is 100
D. counter is 101, number of times is 101
Answer. B
Q-10. What Code Can We Put At The Third Line Of The Definition Of Class B To Invoke Its
Superclass’s Constructor and get output as: 1 2?
class A:
def __init__(self, i = 1):
self.i = i
class B(A):
def __init__(self, j = 2):
________
self.j = j
def main():
b = B()
print(b.i, b.j)
main()
A. super().__init__(self)
B. super().init()
C. A.__init__()
D. A.__init__(self)
Correct Option D
class B(A):
def __init__(self, num):
self.y = num
obj = B(11)
print ("%d %d" % (obj.x, obj.y))
A. AttributeError: ‘B’ object has no attribute ‘x’
B. None 11
C. 11 None
D. 11 11
Answer. A
class B(A):
def __str__(self):
return "B"
class C(B):
def __str__(self):
return "C"
def main():
b = B()
a = A()
c = C()
print(c, b, a)
main()
A. A C B
B. A B C
C. C B A
D. B BB
Answer. C
Q 13: What Will Be The Output Of The Following Code Snippet?
class A:
def __getInfo(self):
return "A's getInfo is called"
def printInfo(self):
print(self.__getInfo(), end = ' ')
class B(A):
def __getInfo(self):
return "B's getInfo is called"
def main():
A().printInfo()
B().printInfo()
main()
A. A’s getInfo is called A’s getInfo is called
B. A’s getInfo is called B’s getInfo is called
C. B’s getInfo is called A’s getInfo is called
D. B’s getInfo is called B’s getInfo is called
Answer. A
A. 13
B. 15
C. 2
D. None of these
Correct : A
Q16: What will be the output of the following Python code?
x = ['ab', 'cd']
for i in x:
i.upper()
print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned
Correct a
i=1
while true:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 2
c) 1 2 3 4 5 6 …
d) Error
Correct d
x = "abcdef"
while i in x:
print(i, end=" ")
a) a b c d e f
b) abcdef
c) iiiiii …
d) error
Correct D
Q19: What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x[:-1]:
print(i, end = " ")
a) aaaaa
b) aaaaaa
c) aaaaaa …
d) a
Correct C
class change:
def __init__(self, x, y, z):
self.a = x + y + z
x = change(1,2,3)
y = getattr(x, 'a')
setattr(x, 'a', y+1)
print(x.a)
a) 6
b) 7
c) Error
d) 0
Correct b
def display(self):
print(self.a)
obj=test()
obj.display()
a) Runs normally, doesn’t display anything
b) Displays 0, which is the automatic default value
c) Error as one argument is required while creating the object
d) Error as display function requires additional argument
Correct C
class fruits:
def __init__(self, price):
self.price = price
obj=fruits(50)
obj.quantity=10
obj.bags=2
obj.material=10
print(obj.quantity+len(obj.__dict__))
a) 13
b) 52
c) 14
d) 60
Ans:C
Q24: What will be the output of the following Python code?
class Demo:
def __init__(self):
pass
def test(self):
print(__name__)
obj = Demo()
obj.test()
a) Error
b) __main__
c) Demo
d) test
Answer: a
x = (i for i in range(3))
for i in x:
print(i)
for i in x:
print(i)
a) 0
1
2
b) error
c) 0 1 2 0 1 2
d) none of the mentioned
Answer: a
Contents of somefile.txt:
content1 = file.read()
content2 = file.readline()
content3 = file.readlines()
content3: ['This is first line.\n', 'This is second line.\n', 'This is third line.\n']
content2:
content3: []
content3: []
D. content1:
content2: This is first line.
content3: ['This is first line.\n', 'This is second line.\n', 'This is third line.\n']
Answer: B
-----------------------------
print (fileobj.tell(10))
C. Error
D. No output
Answer: C
----------------------------------------
print (fileobj.tell())
C. Error
D. No output
Answer: B
---------------------------------------
C Error
D. Hello and
Answer: A
---------------------------------------------------
C Error
Answer: A
---------------------------------------------
D. Error
Answer: B
-----------------------------------------------
B. Error
C. The sum of 0 and 1 is 2
Answer: A
-----------------------------------------------
A. True
B. False
C. Error
Answer: B
------------------------------------------
print("abcdef".find("cd") == "abcdef".rfind("cd"))
A. True
B. False
C. Error
Answer: A
-----------------------------------------
10. Which of the following lines of code will not show a match (assume that 'import re' is used)?
------------------------------------------
import re
print (m.re.pattern)
A. {}
C. a
D. No output
Answer: C
--------------------------------------
A. no difference
B. in 'r+' the pointer is initially placed at the beginning of the file and the pointer is at the end
for 'a'
C. in 'w+' the pointer is initially placed at the beginning of the file and the pointer is at the end
for 'r+'
Answer: B
-------------------------------------
13. How do you change the file position to an offset value from the start?
A. fp.seek(offset, 0)
B. fp.seek(offset, 1)
C. fp.seek(offset, 2)
D. none of the mentioned
Answer: A
-------------------------------------------
14. What happens if no arguments are passed to the file handling 'seek' function?
D. error
Answer: D
-----------------------------------------
15. Which function of file handling is used to read all the characters of a file?
A. read()
B. readcharacters()
C. readall()
D. readchar()
Answer: A
--------------------------------------
16. Which file handling function is used to write all the characters to a file?
A. write()
B. writecharacters()
C. writeall()
D. writechar()
Answer: A
------------------------------------
17. Which file handling function is used to write a list of strings to a file?
A. writeline()
B. writelines()
C. writestatement()
D. writefullline()
Answer: B
---------------------------------------
fo = open("foo.txt", "r+")
line = fo.readline()
fo.close()
A. Compilation Error
B. Syntax Error
C. Displays Output
Answer: C
------------------------------------------
19. What will be the output of the following Python code snippet?
print('abcdefcdghcd'.split('cd', 2))
B. [‘ab’, ‘efcdghcd’]
C. [‘abcdef’, ‘ghcd’]
Answer: A
--------------------------------------
print('ab\ncd\nef'.splitlines())
Answer: A
---------------------------------------
21. What will be the output of the following Python code snippet?
print('Ab!2'.swapcase())
A. AB!@
B. ab12
C. aB!2
D. aB1@
Answer: C
-------------------------------------
22. What will be the output of the following Python code snippet?
print('ab cd ef'.title())
A. Ab cd ef
B. Ab cd eF
C. Ab Cd Ef
Answer: C
--------------------------------------------
23. What will be the output of the following Python code snippet?
print('ab cd-ef'.title())
A. Ab cd-ef
B. Ab Cd-ef
C. Ab Cd-Ef
Answer: C
-----------------------------------------
24. What will be the output of the following Python code snippet?
A. xyyxyyxyxyxxy
B. 12y12y1212x12
C. 12yxyyxyxyxxy
D. xyyxyyxyxyx12
Answer: A
---------------------------------------------
25. What will be the output of the following Python code snippet?
A. xyyxyyxyxyxxy
B. 12y12y1212x12
D. error
Answer: B
-------------------------------------------------
def mk(x):
def mk1():
print("Decorated")
x()
return mk1
def mk2():
print("Ordinary")
p = mk(mk2)
p()
a)
Decorated
Decorated
b)
Ordinary
Ordinary
c)
Ordinary
Decorated
d)
Decorated
Ordinary
Answer: d
def ordi():
print("Ordinary")
ordi
ordi()
a)Ordinary
b)Error
Answer a)
3. What will be the output of the following Python code?
a)
0
0
b)
Zero Division Error
Zero Division Error
c)
0
Zero Division Error
d)
Zero Division Error
0
Answer c)
Answer: c
5. What will be the output of the following Python code?
def f(x):
def f1(*args, **kwargs):
print("*", 5)
x(*args, **kwargs)
print("*", 5)
return f1
@f
def p(m):
p(m)
print("hello")
a)
*****
hello
b)
*****
*****
hello
c) *****
d) hello
Answer d
a) Error
b) Warning
c) 100
d) No output
Answer: c
Answer: a
>>> l=list('HELLO')
>>> p=l[0], l[-1], l[1:3]
>>> 'a={0}, b={1}, c={2}'.format(*p)
a) Error
b) “a=’H’, b=’O’, c=(E, L)”
c) “a=H, b=O, c=[‘E’, ‘L’]”
d) Junk value
Answer: c
9. What will be the output of the following Python code?
>>> hex(255), int('FF', 16), 0xFF
a) [0xFF, 255, 16, 255]
b) (‘0xff’, 155, 16, 255)
c) Error
d) (‘0xff’, 255, 255)
Answer: d
10. The output of the two codes shown below is the same.
>>> bin((2**16)-1)
>>> '{}'.format(bin((2**16)-1))
a) True
b) False
Answer: a
11. What will be the output of the following Python code?
>>> '{a}{b}{a}'.format(a='hello', b='world')
a) ‘hello world’
b) ‘hello’ ‘world’ ‘hello’
c) ‘helloworldhello’
d) ‘hello’ ‘hello’ ‘world’
Answer: c
12. What will be the output of the following Python code?
>>> D=dict(p='hello',q='world')
>>> '{p}{q}'.format(**D)
a) Error
b) 'helloworld'
c) 'hello world'
d) {‘hello’, ‘world’}
Answer: b
13. What will be the output of the following Python code?
>>>'The {} side {1} {2}'.format('bright', 'of', 'life')
a) Error
b) ‘The bright side of life’
c) ‘The {bright} side {of} {life}’
d) No output
Answer: a
14. What will be the output of the following Python code?
>>>'%.2f%s' % (1.2345, 99)
a) ‘1.2345’, ‘99’
b) ‘1.2399’
c) ‘1.234599’
d) 1.23, 99
Answer: b
15. What will be the output of the following Python code?
>>>'%s' %((1.23,),)
a) ‘(1.23,)’
b) 1.23,
c) (,1.23)
d) ‘1.23’
Answer: a
Answer: c
18. The output of which of the codes shown below will be: ‘There are 4 blue birds.’?
a)>>> ‘There are %g %d birds.’ %4 %blue
b) >>>‘There are %d %s birds.’ %(4, ‘blue’)
c) >>>‘There are %s %d birds.’ %[4, blue]
d) >>>‘There are %d %s birds.’ 4, blue
Answer: b
19. What will be the output of the following Python code snippet?
>>>x=3.3456789
>>>'%s' %x, str(x)
a) Error
b) (‘3.3456789’, ‘3.3456789’)
c) (3.3456789, 3.3456789)
d) (‘3.3456789’, 3.3456789)
Answer: b
20. What will be the output of the following Python code?
>>>s='{0}, {1}, and {2}'
>>>s.format('hello', 'good', 'morning')
a) ‘hello good and morning’
b) ‘hello, good, morning’
c) ‘hello, good, and morning’
d) Error
Answer: c
Q21. What will be the output of the following Python code?
print(()or[]or{}or'')
a)()
b)[]
c){}
d)None of the above
Ans d
Q22. What will be the output of the following Python code?
print(['f', 't']or[bool('spam')])
a) ['f', 't']
b)spam
c)’spam’
d)None of the above
Ans a
a)Invalid attribute
b)tom
c)()
d)None
Ans b
Answer: c
>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld
Answer: a
>>>chr(ord('A'))
a) A
b) B
c) a
d) Error
Answer: a
>>>t=(1,2,4,3)
>>>t[1:3]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer: c
>>>t2 = (1, 2, 3, 4)
>>>t1 < t2
a) True
b) False
c) Error
d) None
Answer: b
>>>t = (1, 2)
>>>2 * t
a) (1, 2, 1, 2)
b) [1, 2, 1, 2]
c) (1, 1, 2, 2)
d) [1, 1, 2, 2]
Answer: a
a=1,2,3,4
print(a)
a) (1, 2, 3, 4)
b) 1
c) 4
d) 1,2,3,4
Answer: a
>>> a=(1,2)
>>> b=(3,4)
>>> c=a+b
>>> c
a) (4,6)
b) (1,2,3,4)
c) Error as tuples are immutable
d) None
Answer: b
>>> a=(2,3,1,5)
>>> a.sort()
>>> a
a) (1,2,3,5)
b) (2,3,1,5)
c) None
d) Error, tuple has no attribute sort
Answer: d
Answer: c
59. The ____________ function removes the first element of a set and the last element of a list.
a) remove
b) pop
c) discard
d) dispose
Answer: b
s=set([1, 2, 3])
s.union([4, 5])
print(s)
a){1, 2, 3}
b)[1,2,3]
c){1,2,3,4,5}
d)[1,2,3,4,5]
Ans: a
numbers.append([5,6,7,8])
print(len(numbers))
a) 4
b) 5
c) 8
d) 12
Answer: b
>>> numbers.extend([5,6,7,8])
>>> len(numbers)
a) 4
b) 5
c) 8
d) 12
Answer: c
34. what is the output of following code?
list1=[10,10,10,10]
for x in list1:
list1.remove(x)
print(list1)
a) [ ]
b) [10,10,10,10]
c) [10,10]
d) Error
Answer: c
veggies.insert(veggies.index('broccoli'), 'celery')
print(veggies)
print(m)
37. What will be the output of the following Python code snippet?
print('ab\ncd\nef'.splitlines())
a) [‘ab’, ‘cd’, ‘ef’]
b) [‘ab\n’, ‘cd\n’, ‘ef\n’]
c) [‘ab\n’, ‘cd\n’, ‘ef’]
d) [‘ab’, ‘cd’, ‘ef\n’]
Answer: a
38. What will be the output of the following Python code snippet?
print('Ab!2'.swapcase())
a) AB!@
b) ab12
c) aB!2
d) Error
Answer: c
39. What will be the output of the following Python code snippet?
print('ab cd-ef'.title())
a) Ab cd-ef
b) Ab Cd-ef
c) Ab Cd-Ef
d) None of the mentioned
Answer: c
40. What will be the output of the following Python code snippet?
print('abcdef12'.replace('cd', '12'))
a) ab12ef12
b) abcdef12
c) ab12efcd
d) none of the mentioned
Answer: a
41. What will be the output of the following Python code snippet?
print('abef'.replace('cd', '12'))
a) abef
b) 12
c) error
d) none of the mentioned
Answer: a
a) xyyxyyxyxyxxy
b) 12y12y1212x12
c) 12yxyyxyxyxxy
d) xyyxyyxyxyx12
Answer: a
print('ab12'.isalnum())
a) True
b) False
c) None
d) Error
Answer: a
print('ab,12'.isalnum())
a) True
b) False
c) None
d) Error
Answer: b
count={}
count[(1,2,4)] = 5
count[(4,2,1)] = 7
count[(1,2)] = 6
count[(4,2,1)] = 2
tot = 0
for i in count:
tot=tot+count[i]
print(len(count)+tot)
a) 25
b) 17
c) 16
d) Tuples can’t be made keys of a dictionary
Answer: c
a={}
a[2]=1
a[1]=[2,3,4]
print(a[1][1])
e) [2,3,4]
f) 3
g) 2
h) An exception is thrown
Answer: b
Answer: c
65. What will be the output of the following Python code snippet?
total={}
def insert(items):
if items in total:
total[items] +=1
else:
total[items]=1
insert('Apple')
insert('Ball')
insert('Apple')
print(len(total))
a) 3
b) 1
c) 2
d) 0
Answer: c
66. What will be the output of the following Python code snippet?
a ={}
a[1]=1
a['1']=2
a[1]=a[1]+1
count =0
foriin a:
count += a[i]
print(count)
a) 1
b) 2
c) 4
d) Error, the keys can’t be a mixture of letters and numbers
Answer: c
67. What will be the output of the following Python code snippet?
numbers ={}
letters ={}
comb ={}
numbers[1]=56
numbers[3]=7
letters[4]='B'
comb['Numbers']= numbers
comb['Letters']= letters
print(comb)
Answer: d
a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”
Answer: a
70. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method
Answer: b
a={1:"A",2:"B",3:"C"}
print(a.get(5,4))
Answer: d
73. The character Dot (that is, ‘.’) in the default mode, matches any character other than
_____________
a) caret
b) ampersand
c) percentage symbol
d) newline
Answer: d
74. The expression a{5} will match _____________ characters with the previous regular
expression.
a) 5 or less
b) exactly 5
c) 5 or more
d) exactly 4
Answer: b
a) ‘^’, ‘$’
b) ‘$’, ‘^’
c) ‘$’, ‘?’
d) ‘?’, ‘^’
Answer: a
a) [“hello”]
b) [ ]
c) hello
d) hello world
Answer: b
a) re.A
b) re.U
c) re.I
d) re.X
Answer: c
78. Choose the function whose output can be: <_sre.SRE_Match object; span=(4, 8),
match=’aaaa’>
a) re.search(‘aaaa’, “alohaaaa”, 0)
b) re.match(‘aaaa’, “alohaaaa”, 0)
c) re.match(‘aaa’, “alohaaa”, 0)
d) re.search(‘aaa’, “alohaaa”, 0)
Answer: a
func(x)
print('x is now', x)
a) x is now 50
b) x is now 2
c) x is now 100
d) None of the mentioned
Answer: a
b)
x is 50
Changed global x to 2
Value of x is 2
c)
x is 50
Changed global x to 50
Value of x is 50
Answer: b
a) 4
b) 5
c) 1
d) An exception is thrown
Answer: a
b)
45
56
c)
10
20
d) Syntax Error
Answer: a
83. How do you get the name of a file from a file object (fp)?
a) fp.name
b) fp.file(name)
c) self.__name__(fp)
d) fp.__name__()
Answer: a
a) fp.name = ‘new_name.txt’
b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)
Answer: b
a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()
Answer: a
a) writeline()
b) writelines()
c) writestatement()
d) writefullline()
Answer: b
87. What will be the output of the following Python code? (If entered name is psit)
import sys
print 'Enter your name: ',
name = ''
while True:
c = sys.stdin.read(1)
if c == '\n':
break
name = name + c
a) psit
b) psit, psit
c) psi
d) None of the mentioned
Answer: a
a) file.writelines(sequence)
b) fileObject.writelines()
c) fileObject.writelines(sequence)
d) none of the mentioned
Answer: a
a) [1, 2, 3]
b) [0, 1, 2]
c) error
d) none of the mentioned
Answer: c
def fun(name,age):
print(name)
print(age)
fun(25,"tom")
a)25
tom
b)25
‘tom’
c) tom
25
d)tom
‘25’
Answer a
def fun(name,age):
print("name is ",name)
print("age is ",age)
fun(age=25,name="jack")
a) name is jack
age is 25
b) name is 25
age is ‘jack’
c)Error
Answer a
def fun(name,age):
print("name is ",name)
print("age is ",age)
fun(25,"Harry")
a) name is 25
age is Harry
b) Error
c)name is Harry
age is 25
Answer a
def f1(list1):
list1[0]=100
list2=[1,2,3]
f1(list2)
print("list1 is ",list1)
a)list1 is [100,2,3]
b)Error
c)list1 is [1,2,3]
Answer b
def f2(list1):
list1[0]=500
print("list1 is ",list1)
list2=[1,2,3]
f2(list2)
print("list2 is ",list2)
a) list1 is [500, 2, 3]
list2 is [500, 2, 3]
b)Error
c) list1 is [500, 2, 3]
list2 is [1, 2, 3]
Answer a
def f3(list1):
list1[0]=500
print("list1 is ",list1)
list2=[1,2,3]
f3(list2[:])
print("list2 is ",list2)
a) list1 is [500, 2, 3]
list2 is [1, 2, 3]
b)Error
c) list1 is [500, 2, 3]
list2 is [500, 2, 3]
Answer a
def function1(*x):
print(x)
function1()
a)Error
b)*
c)()
Answer c
def function2(*k):
print(type(k))
function2()
a)tuple
b)dictionary
c)string
d)list
Answer a
def function2(**x):
print(type(x))
function2()
a)tuple
b)dictionary
c)string
d)list
Answer b
y=8
z = lambda x : x * y
print (z(6,6) )
a)36
b)48
c)Error
Answer c
7. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing operation?
a) print(list1[0])
b) print(list1[:2])
c) print(list1[:-2])
d) all of the mentioned
Answer: d
>>> names[-1][-1]
a) A
b) Daman
c) Error
d) n
View Answer
Answer: d
12. To add a new element to a list we use which command?
a) list1.add(5)
b) list1.append(5)
c) list1.addLast(5)
d) list1.addEnd(5)
Answer: b
Answer: d
if 'amir' in names1:
print(1)
else:
print(2)
a) None
b) 1
c) 2
d) Error
Answer: c
numbers.append([5,6,7,8])
print(len(numbers))
a) 4
b) 5
c) 8
d) 12
Answer: b
>>> numbers.extend([5,6,7,8])
>>> len(numbers)
a) 4
b) 5
c) 8
d) 12
Answer: c
list1=[10,10,10,10]
for x in list1:
list1.remove(x)
print(list1)
a) [ ]
b) [10,10,10,10]
c) [10,10]
d) Error
Answer: c
veggies.insert(veggies.index('broccoli'), 'celery')
print(veggies)
print(m)
21. What will be the output of the following Python code snippet?
print('ab\ncd\nef'.splitlines())
22. What will be the output of the following Python code snippet?
print('Ab!2'.swapcase())
a) AB!@
b) ab12
c) aB!2
d) Error
Answer: c
23. What will be the output of the following Python code snippet?
print('ab cd-ef'.title())
a) Ab cd-ef
b) Ab Cd-ef
c) Ab Cd-Ef
d) None of the mentioned
Answer: c
24. What will be the output of the following Python code snippet?
print('abcdef12'.replace('cd', '12'))
a) ab12ef12
b) abcdef12
c) ab12efcd
d) none of the mentioned
Answer: a
25. What will be the output of the following Python code snippet?
print('abef'.replace('cd', '12'))
a) abef
b) 12
c) error
d) none of the mentioned
Answer: a
a) xyyxyyxyxyxxy
b) 12y12y1212x12
c) 12yxyyxyxyxxy
d) xyyxyyxyxyx12
Answer: a
print('Hello!2@#World'.istitle())
a) True
b) False
c) None
d) error
Answer: a
28. What will be the output of the following Python code snippet?
print('abc'.islower())
a) True
b) False
c) None
d) Error
Answer: a
print('ab12'.isalnum())
a) True
b) False
c) None
d) Error
Answer: a
print('ab,12'.isalnum())
a) True
b) False
c) None
d) Error
Answer: b
print("ccdcddcd".find("c"))
a) 4
b) 0
c) Error
d) True
Answer: b
Answer: c
>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld
Answer: a
Answer: b
>>>chr(ord('A'))
a) A
b) B
c) a
d) Error
Answer: a
>>>t=(1,2,4,3)
>>>t[1:3]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer: c
>>>t1 = (1, 2, 4, 3)
>>>t2 = (1, 2, 3, 4)
>>>t1 < t2
a) True
b) False
c) Error
d) None
Answer: b
>>>t = (1, 2)
>>>2 * t
a) (1, 2, 1, 2)
b) [1, 2, 1, 2]
c) (1, 1, 2, 2)
d) [1, 1, 2, 2]
Answer: a
a=1,2,3,4
print(a)
a) (1, 2, 3, 4)
b) 1
c) 4
d) 1,2,3,4
Answer: a
>>> a=(1,2)
>>> b=(3,4)
>>> c=a+b
>>> c
a) (4,6)
b) (1,2,3,4)
c) Error as tuples are immutable
d) None
Answer: b
>>> a=(2,3,1,5)
>>> a.sort()
>>> a
a) (1,2,3,5)
b) (2,3,1,5)
c) None
d) Error, tuple has no attribute sort
Answer: d
Answer: c
48. The ____________ function removes the first element of a set and the last element of a list.
a) remove
b) pop
c) discard
d) dispose
Answer: b
s=set([1, 2, 3])
s.union([4, 5])
print(s)
a){1, 2, 3}
b)[1,2,3]
c){1,2,3,4,5}
d)[1,2,3,4,5]
Ans: a
1. What is the output of the following code?
class EmployeeData:
def __init__(self, sal=0, age=0):
self.sal = sal
self.age = age
def getData(self):
print("{0}+{1}j".format(self.sal,self.age))
empdata = EmployeeData()
empdata.getData()
a) Shows no data
b) 0+0j
c) Shows error
d) None of the above
def display(self):
print(self.a)
obj=test()
obj.display()
a) The program has an error because constructor can’t have default arguments
b) Nothing is displayed
c) “Hello World” is displayed
d) The program has an error
3. What is the output of the following code?
class Change:
def __init__(self, x, y, z):
self.a = x + y + z
x = Change(1,2,3)
y = getattr(x, 'a')
print(x.a)
a) 6
b) 7
c) Error
d) 0
def display(self):
print(self.b)
obj=A("Hello")
del obj
a) True
b) False
5. What is the output of the following code?
class Test:
def __init__(self):
self.variable = 'Old'
self.Change(self.variable)
obj=Test()
print (obj.variable)
a) “Old”
b) “New”
c) Shows error
d) None of the above
class Fruits:
def __init__(self, price):
self.price = price
obj=Fruits(50)
obj.quantity=10
obj.bags=2
print(obj.quantity+len(obj.__dict__))
a) 12
b) 52
c) 13
d) 60
7. What is the output of the following code?
class Demo:
def __init__(self):
pass
def test(self):
print(__name__)
obj = Demo()
obj.test()
a) __main__
b) __name__
c) main
d) Shows error
class Stud:
def __init__(self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
a) True
b) False
c) No output
d) Shows error
9. What is the output of the following piece of code?
class objects:
def __init__(self):
self.colour = None
self._shape = "Circle"
obj=objects()
print(obj._objects_shape)
a) The program runs fine because name mangling has been properly implemented
b) Error because the member shape is a protected member
c) Error because the proper syntax for name mangling hasn’t been implemented
d) Error because the member shape is a private member
class Sales:
def __init__(self, id):
self.id = id
id = 100
val = Sales(123)
print (val.id)
a) Syntax error
b) 100
c) 123
d) None of the above
11. Which of the following statements are true for the given code snppet?
class A:
def __init__(self, i = 0):
self.i = i
class B(A):
def __init__(self, j = 0):
self.j = j
def main():
b = B()
print(b.i)
print(b.j)
main()
class A:
def __init__(self):
self.calcI(30)
print("i from A is", self.i)
class B(A):
def __init__(self):
super().__init__()
b = B()
class Demo:
count = 0
def __init__(self):
self.count += 1
def get_count(self):
return self.count
demo = Demo()
demo1 = Demo()
print (demo.get_count())
a) 1
b) 2
c) 0
d) None of the above
class Demo:
count = 0
def __init__(self):
Demo.count += 1
def get_count(self):
return Demo.count
demo1 = Demo()
demo2 = Demo()
demo3 = Demo()
print (demo1.get_count())
a) 1
b) 2
c) 3
d) None of the above
class P:
def __init__(self):
self.__x=100
self.y=200
def print(self):
print(self.__x, self.y)
class C(P):
def __init__(self):
super().__init__()
self.__x=300
self.y=400
d = C()
d.print()
a) 300 400
b) 100 400
c) 100 200
d) 300 200
16. What is the output of the following code?
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def display(self):
return self.__b
obj = Demo()
print(obj.a)
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private
member
c) The program runs fine and 1 is printed
d) The program has an error as you can’t name a class member using __b
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def display(self):
return self.__b
obj = Demo()
print(obj.__b)
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private
member
c) The program has an error because b is private and hence can’t be printed
d) The program runs fine and 1 is printed
class Demo:
def __init__(self):
__a = 1
self.__b = 1
self.__c__ = 1
__d__= 1
a) __a
b) _b
c) __c__
d) __d__
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
return self.__b
obj = Demo()
print(obj.get())
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private
member
c) The program has an error because b is private and hence can’t be printed
d) The program runs fine and 1 is printed
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
return self.__b
obj = Demo()
obj.a=45
print(obj.a)
class Fruits:
def __init__(self):
self.price = 100
self.__bags = 5
def display(self):
print(self.__bags)
obj=Fruits()
obj.display()
a) The program has an error because display() is trying to print a private class member
b) The program runs fine but nothing is printed
c) The program runs fine and 5 is printed
d) The program has an error because display() can’t be accessed
class Student:
def __init__(self):
self.marks = 97
self.__cgpa = 8.7
def display(self):
print(self.marks)
obj=Student()
print (obj._student__cgpa)
class A():
pass
class B():
pass
class C(A,B):
pass
a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance
class A:
def __init__(self):
self.__i = 1
self.j = 5
def display(self):
print(self.__i, self.j)
class B(A):
def __init__(self):
super().__init__()
self.__i = 2
self.j = 7
c = B()
c.display()
a) 27
b) 15
c) 17
d) 25
class A:
def print_hello(self):
print ("In class A")
class B(A):
pass
c = C()
c.print_hello()
class B(A):
pass
c = C()
a = A()
a.print_hello()
c.print_hello()
a) In class A
In class A
In class C
b) In class C
In class A
c) In class C
d) None of the above
class A:
def __init__(self,x):
self.x = x
def count(self,x):
self.x = self.x+1
class B(A):
def __init__(self, y=0):
A.__init__(self, 3)
self.y = y
def count(self):
self.y += 1
def main():
obj = B()
obj.count()
print(obj.x, obj.y)
main()
a) 30
b) 01
c) 31
d) None of the above
28. What is the output of the following piece of code when executed in the Python shell?
>>> class A:
pass
>>> class B(A):
pass
>>> obj=B()
>>> isinstance(obj,A)
a) True
b) False
c) Wrong syntax for isinstance() method
d) Invalid method for classes
29. Method issubclass() checks if a class is a subclass of another class. True or False?
a) True
b) False
30. What is the output of the following piece of code?
class A:
def one(self):
return self.two()
def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj2=B()
print(obj2.two())
a) A
b) Exception is thrown
c) AB
d) B
a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to certain
class members
c) Focuses on variables and passing of variables to functions
d) Allows for implementation of elegant software that is well designed and easily modified
class Demo:
def __new__(self):
self.__init__(self)
print("Demo's __new__() invoked")
def __init__(self):
print("Demo's __init__() invoked")
class Derived_Demo(Demo):
def __new__(self):
print("Derived_Demo's __new__() invoked")
def __init__(self):
print("Derived_Demo's __init__() invoked")
def main():
obj1 = Derived_Demo()
obj2 = Demo()
main()
a) A.__init__(self)
b) B.__init__(self)
c) A.__init__(B)
d) B.__init__(A)
36. What is the output of the following code?
class Test:
def __init__(self):
self.x = 0
class Derived_Test(Test):
def __init__(self):
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y)
main()
a) 01
b) 00
c) Error because class B inherits A but variable x isn’t inherited
d) Error because when object is created, argument must be passed like Derived_Test(1)
class A():
def disp(self):
print("A disp()")
class B(A):
pass
obj = B()
obj.disp()
class A:
def __init__(self, x= 1):
self.x = x
class der(A):
def __init__(self,y = 2):
super().__init__()
self.y = y
def main():
obj = der()
print(obj.x, obj.y)
main()
a) Single-level
b) Double-level
c) Multiple
d) Multi-level
40. Which of the following statements is not true?
a) A non-private method in a superclass can be overridden
b) A derived class is a subset of superclass
c) The value of a private variable in the superclass can be changed in the subclass
d) When invoking the constructor from a subclass, the constructor of superclass is
automatically invoked
class A:
def __init__(self,x):
self.x = x
def count(self,x):
self.x = self.x+1
class B(A):
def __init__(self, y=0):
A.__init__(self, 3)
self.y = y
def count(self):
self.y += 1
def main():
obj = B()
obj.count()
print(obj.x, obj.y)
main()
a) 30
b) 31
c) 01
d) None of the above
class A:
def test1(self):
print(" test of A called ")
class B(A):
def test(self):
print(" test of B called ")
class C(A):
def test(self):
print(" test of C called ")
class D(B,C):
def test2(self):
print(" test of D called ")
obj=D()
obj.test()
class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()
a) test of B called
test of C called
b) test of C called
test of B called
c) test of B called
test of C called
test of A called
d) Error, all the three classes from which D derives has same method test()
a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to certain
class members
c) Focuses on variables and passing of variables to functions
d) Allows for objects of different types and behaviour to be treated as the same general
type
46. What is the output of the following piece of code?
class A:
def __init__(self,x=3):
self._x = x
class B(A):
def __init__(self):
super().__init__(5)
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main()
a) 5
b) 3
c) Error, class member x has two values
d) Error, protected class member can’t be accessed in a subclass
class A:
def __str__(self):
return '1'
class B(A):
def __init__(self):
super().__init__()
class C(B):
def __init__(self):
super().__init__()
def main():
obj1 = B()
obj2 = A()
obj3 = C()
print(obj1, obj2,obj3)
main()
a) 1 1 1
b) 1 2 3
c) ‘1’ ‘1’ ‘1’
d) An exception is thrown
class Demo:
def __init__(self):
self.x = 1
def change(self):
self.x = 10
class Demo_derived(Demo):
def change(self):
self.x=self.x+1
return self.x
def main():
obj = Demo_derived()
print(obj.change())
main()
a) 11
b) 2
c) 1
d) An exception is thrown
49. A class in which one or more methods are only implemented to raise an exception is
called an abstract class. True or False?
a) True
b) False
50. What is the output of the following piece of code?
class A:
def __repr__(self):
return "1"
class B(A):
def __repr__(self):
return "2"
class C(B):
def __repr__(self):
return "3"
o1 = A()
o2 = B()
o3 = C()
print(obj1, obj2, obj3)
a) 1 1 1
b) 1 2 3
c) ‘1’ ‘1’ ‘1’
d) An exception is thrown
a) ‘Hello’
b) “hello”
c) Hello
d) Error
class computer:
def writecode(self,text):
print(text,"written in editor")
def execute(self):
print("Code executed")
class student:
def dolabassignment(self,computer,assignment):
computer.writecode(assignment)
computer.execute()
c=computer()
s=student()
s.dolabassignment(c,"Assignment Code")
a) Aggregation
b) Association
c) Composition
d) None of the above
56. Following code shows the concept of________.
class Players:
def __init__(self,name):
self.name=name
class team:
def __init__(self):
self.players=[]
def addplayers(self,player):
self.players.append(player)
P=Players("Sachin")
t=team()
t.addplayers(P)
print(t.players[0].name)
a) Aggregation
b) Association
c) Composition
d) None of the above
57. following code shows the concept of __________-.
class Room:
pass
class Building:
def __init__(self,room_count):
self.rooms=[]
for i in range(0,room_count):
r=Room()
self.rooms.append(r)
def __del__(self):
print("All rooms destroyed")
del self.rooms
b=Building(3)
del(b)
a) Aggregation
b) Association
c) Composition
d) None of the above