AN®RA HR
LZ wnat does the folowing Python Program print out?
strl = "Hello"
‘there!
(bob)
a) Hellothere
b) Hello there
©) “Hello”there’
4d) 0
e) Hello
o/nat does the following Python program print out?
x= 140"
y = int(x) +2
print (y)
a) 42
b) 2
<) intao2
¢) 402
3. How would you use the index operator [] to print out the letter q from the following string?
x = 'From
[email protected]'
a) print(x{s})
b)_print(xtq))
cc) print(x{9})
d) print(x[(7})
e) Print(x.index(q))
4. How would you use string slicing [:] to print out ‘uct! from the following string?
x = ‘From
[email protected]'
a) print(x(14/17))
b)_print(x[14+17))
o) print(x(24:3})
d)_print(x(15:18])
e) print(x{14:17))
Page 1of 17AN#RA s
or is the iteration variable in the following Python code?
+ letter in ‘banana’:
Print (letter)
a) ‘banana’
b) in
¢) ‘b’,’a’,’n',’a’,’n’,"0
4) for
e) letter
6. What does the following Python code print out?
Vv print (1en (‘banana’) *7)
a) banana7
b)_bananabananabananabananabananabananabanana .
0
d) 42
7. How would you print out the following variable in all upper case in Python?
greet = 'Hello Bob!
a) _print(upper(greet))
b) puts(greet.ucase);
c) _print(greet.upper())
d) inti=o;
char ¢;
while (greet[i]){
c=greetli;
putchar(toupper(c));
itt;
8. Which of the following is not a valid string method in Python?
a) Shutil.out()
b) split()
¢) join)
d)_startswith()AN*RA ik
9. What will the following Python code print out? =
data = ‘From
[email protected] Sat Jan 5 09:14:16 200g"
pos = data.find('.')
print (data (pos:pos+3])
a) uct
b) mar
) wma
d) 09:14
10. Which of the following string methods removes whitespace from both the beginning and
end of a string?
a) remove (")
b) trim ()
¢) Itrim()
4d) strip()
11. What is stored in a "file handle" that is returned from a successful open() call?
: a) The handle is a connection to the file's data
b) All the data from the file is read into memory and stored in the handle
)_ The handle contains the first 10 lines of a file
d) The handle has a list of all of the files in a particular folder on the hard drive
12. What do we use the second parameter of the open() call to indicate?
a) The list of folders to be searched to find the file we want to open
b) What disk drive the file is stored on
c) How large we expect the file to be
d) Whether we want to read data from the file or write data to the file
13. What Python function would you use if you wanted to prompt the user for a file name to
open?
a) file_input()
b) gets()
©) accept ()
d) input()
14, What is the purpose of the newline character in text files?
a) It adds a new network connection to retrieve files from the network
'b) It indicates the end of one line of text and the beginning of another line of text
¢) It enables random movement throughout the file
4) It allows us to open more than one files and read them in a synchronized
mannerAN@RA 4
15. If we open a file as follows:
xfi1@ ™ Open "mbox. txt")
What statement would we use to read the file one line at a time?
a) while ( getline (xfile,line) ){
b) for line in xfile:
€) READ (xfile,*,END=10) line
d) while (
) (
16. What is the purpose of the following Python code?
fhand = open{*mbox.txt
x=0
for line’ in fhand
xexel
print (x)
a) Count the lines in the file ‘mbox.txt’
b) Remove the leading and trailing spaces from each line in mbox.txt
©) Count the number of characters in each line in the file
d) Reverse the order of the lines in mbox.txt
47. if you write a Python program to read a text file and you see extra blank lines in the output
that are not present in the file input as shown below, what Python string function will likely
solve the problem?
[email protected]
[email protected]
[email protected]
rjlowe@iupvi edu
stephen.marquardéuct .ac.2a
[email protected]
From: [email protected]
From: [email protected]
a) Must)
b) startswith()
c) sjust(\n’)
d) find()
e)_strip()
Page 4 of 17AN®RA ih
18. The following code sequence fails with a traceback when the user enters a file that does not
exist. How would you avoid the traceback and make it so
message when a bad file name was entered?
fname = input (‘Enter the file name: ')
fhand = open(fname)
you could print out your own error
a) begin /rescue / end
b) signal handlers
©) try/except
a) iffelse
19. What does the following Python code do?
fhand = open ('mbox=short..txt")
inp = fhand.read()
a) Checks to see if the file exists and can be written
») Prompts the user for a file name
©) Turns the text in the file into a graphic image like a PNG or JPG
4) Reads the entire file into the variable inp as a string
20. How are "collection" variables different from normal variables?
2) Collection variables merge streams of output into a single stream
®) Collection variables can store multiple values in a single variable
<) Collection variables pull multiple network documents together
4) Collection variables can only store a single value
21. What are the Python keywords used to construct a loop to iterate through a list?
a) for/in
b) _iter_()
) def /return
d) foreach / in
22. For the following list, how would you print out 'Sally'?
friends = [ ‘Joseph, 'Glenn', ‘Sally']
a) print(friends3})
)_print(friends('sally'})
©) print(friends{2-1))
4) print(friends(2})
Page 5 of 17AN®RA
would
23, what would the following Python code print out?
{rvitlO) © the
print (fruity
ii
“Nothing would print - the program fails with a traceback
+24, Which of the following Python statements would print out the length of a list stored in the
variable data?
a) print(len(data))
'b) print(strien(data))
©) print(length(data))
4) print(sort(data).Len)
e) print(data.tength())
f)_ print(data.length)AN#RA a
37, Which of the following slicing operations will produce the list (12, 3]?
t = (9 41, 12, 3, 74, 15)
a) (12:3)
b) t{1:3)
2) t24)
d) (2:2)
e) th)
28. What list method adds a new item to the end of an existing list?
a) push)
») popi)
©) append()
d) forward()
e) index()
f) addi)
29. What will the following Python code print out?
friends = [‘Joseph', ‘Glenn’, 'sally')
friends.sort ()
print (friends {01)
a) friends
b) Glenn
©) Joseph
d) Sally
30. How are Python dictionaries different from Python lists?
a) Python lists can store strings and dictionaries can only store words
b) Python lists maintain order and dictionaries do not maintain order
¢) Python dictionaries can store duplicates and list cannot
d) Python lists store multiple values and dictionaries store a single value
31. What is a term commonly used to describe the Python dictionary feature in other
programming languages?
a) Closures
b) Sequences
©) Associative arrays
d) Lambdas
Page 7 of 17AN#®RA i
32. What wea ~~ following Python code print out?
‘ ct ()
print (Stuft{*candy'])
a) 2
b) 0
©) The program would fail with an error
d) Candy
e) None
33, What Would the following Python code print out?
stuff = dict ()
print (stuff.get (‘candy', -1))
a) 0
b) The program would fail with a traceback
©) ‘candy’
@) 2
+34, What is @ common use of Python dictionaries in a program?
2) Computing an average of a set of numbers
b) Sorting a list of names into alphabetical order
€) Building a histogram counting the occurrences of various strings ina file
4). Splitting a line of input into words using a space a5 2 delimiter
python is equivalent to the following sequence of statements
35, Which of the following lines of
assuming that counts are a dictionary?
if key in counts:
counts[key] = counts
else:
counts{key) = 2
[key] +1
a) counts{key] = counts.get(key, -1) +1
b) _counts{key] = key +1
c)_counts{key] = counts.get(key, 0) +1
d)_counts{key) = {counts{key) * 1) +1
e) counts{key] = (key in counts) +1
Page 8 of 17AN#®RA ME Vid
36. In the following Python, what does the for loop iterate thr jh?
6. In the following Python, wh loop iterate throug!
x= dict()
for y in x
a) It loops through all the dictionaries in the program
b) Itloops through the values in the dictionary
©) tt loops through the integers in the range from zero through the length of the dictionary
4d) Itloops through the keys in the dictionary
37. Which method in a dictionary object gives you a list of the values in the dictionary?
a) keys()
b) items()
©) values()
4) each)
e) all)
38. What is the purpose of the second parameter of the get() method for Python dictionaries?
2) Analternate key to use if the first key cannot be found
b) The value to retrieve
©) To return a default value if the key is not found
d) The key to retrieve
39. What is the difference between a Python tuple and Python list?
2) sts maintain the order of the items and tuples do not maintain order
®) Tuples can be expanded after they are created and lists cannot
¢) Lists are mutable and tuples are not mutable
4) Lists are indexed by integers and tuples are indexed by strings
40. Which of the following methods work both in Python lists and Python tuples?
2) sort()
b) append()
©) index()
4) pop()
e) reverse()
41. What will end up in the variable y after this code is executed?
te Veer a
Page 9 of 17AN#RA ,
a4
b) Adictionary with the key 3 mapped to the value 4
©) Atwo-item tuple
4) 3
e) Atwortem list
42. In the following Python code, what will end up in the variable y?
x ~ (Yehuck': 1, ‘fred’ : 42, "Jan’: 100)
y = x.dtems ()
a) Alist of integers
b) Atuple with three integers
©) Alist of strings
4) Alist of tuples
43. Which of the following tuples is greater than xin the following Python sequence?
ee
a) (5,0, 300)
b) (0, 1000, 2000)
<) (6,0,0)
d) (4, 100, 200),
44, What does the following Python code accomplish, assuming the c is a non-empty
dictionary?
tmp = list ()
for k, v in c.items() +
tmp.append( (v, k) )
It creates a list of tuples where each tuple is a value, key pair
all the values in the dictionary
fall the values in the dictionary
a)
b) It computes the largest of
q)_It computes the average oF
d)_It sorts the dictionary based on its key values
\fthe variable data is a Python list, how do we sort it in reverse order?
a) data.sort-reverse()
Page 10 of 17AN#®RA HR
b) data = data.sort(-1)
¢) data.sort(reverse=True)
d) data = sortrevidata)
46, Using the following tuple, how would you print 'Wed'? ae
days = ('Non', ‘Tue', ‘Wed’, ‘Thu’, ‘Frit, ‘Sat', ‘Sunty
a) print(days.get(1,-1))
b) print(days{a))
©) print{days(2)]
4) print(days(2))
) print(days(2))
f)_printidays{2})
47. in the following Python loop, why are there two iteration variables (k and v)?
c= ('a"sl0, "b's1, 'c':22)
for k, v in c.items()
2) Because the keys for the dictionary are strings
'b)_ Because the items() method in dictionaries returns a list of tuples
©) Because for each item we want the previous and current key
) Because there are two items in the dictionary
48. Given that Python lists and Python tuples are quite similar - when might you prefer to use a
tuple over a list?
2) Fora list of items you intend to sort in place
5) For a list of items that will be extended as new items are found
©) Fora temporary variable that you will use and discard without modifying
4) For a list of items that want to use strings as key values instead of integers
48. Which of the Following Is Required to Create a New instance of the Class?
a) Constructor
b) Aclass
©) Avalue-returning method
4) An object :
80. Which of The Following Can Be Used to Invoke The __init__ Method in B From A, Where Als a
Subclass Of B?
a) super().__init_()
») super(). init__(self)
Page 11 of 17in
a) B._ init__(self)
51. which of The Following Statements Are Correct About The Given Code Snippet?
class Ay
def _init
£4
e148 BIA):
init
belt. = 3
def main():
= 80
int (b. i)
int (b.3)
nai)
a) Class B inherits A, but the data field “i” in A is not inherited.
b) Class B inherits A, thus automatically inherits all data fields in A.
c) When you create an object of B, you must pass an argument such as 8(5)-
d) The data field “j” cannot be accessed by object b.
(self, i = 0):
Lf, 9 = OF
.
52. What Will Be the Output of The Following Code Snippet?
class A:
def init__(self):
Self.calct (30)
print ("i from A is", self.i)AN#RA
‘53, What will Be the Output Of The Following Code Snippet?
Bankaccount
ef _ init__(self)
self. balance
Jef withdraw(self, amount)
elf.balance -= amount
return self.balance
def deposit (self, amount):
self.balance += amount
return self.balance
b
BankAccount ()
BankAccount ()
print a.deposit (100)
Print b.deposit (50)
Print a.withdraw (10)
Print b.withdraw (10)
A.10050,0,0
8 Error
C.10050,0,40
D. 100, 50, Error, Error
54. What Will Be The Output Of The Following Code Snippet?
class A:
def f(self):
return self.g()
def g(self):
return
class B(A):
print a.f(), bf)
print a.g(), b.g()
HR
Page 13 of 17AN#®RA 4
AAA
8B
BAB
AB
AA
D.BA
BA
class Robot:
se"Represents a robot, with a name.
# A class variable, counting the number of robots
population = 0
det init__(self, name!
initializes the dat
self.name = name
print "(initializing ()"-format(self.name))
# When this person is created, the robot
4# adds to the population
Robot population += 1
def die(self):
‘1am dying
print("{) is being destroyed!" format{self.name))
Robot.population = 1
if Robot.population =
print("{} was the last ‘one.".format(self.name))
else:
print("There are still {:d} robots working." format(
Robot.population))
def say_hilself):
‘Greeting by the robot.
Yeah, they can do that."
print("Greetings, my masters call me {)."format{self.name))
Page 14 of 17HR
AN#RA
exessmetiod
oes aon ation."
“eprnts the current POPY*' format{cls.population))
je have {:d) robots
am write the output of the following questions. Note- Questions are in a
program writ
print(
gased on the above
continuation
© droid = Robot("R2-D2")
droid1.say_hil)
Robot.how_many()
56.
droid2 = Robot("C-3PO")
droid2.say_hil)
Robot. how_many()
57.
droid2.die()
Robot. how_many()
class SchoolMember:
“Represents any school member.
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {})'.format(self.name))
def tell(self):
“Tell my details.
print('Name:"{}" Age:"{)"".format(self.name, self.age), end=" ")
class Teacher(SchoolMember):
“Represents a teacher.
def _ init__(self, name, age, salary):
‘SchoolMember.__init__(self, name, age)
self.salary = salary
Print('(Initialized Teacher: {})'.format(self.name))
def teliiself):
SchoolMember.tell(self)
Print('Salary: "{:d)"' format(self.salary))
class Student(SchoolMember):
Page 15 of 17def telliself):
Drint(’Marks: "(:d)""format(self.marks))
Based on the above program write the output of the following questions. Note- Questions are ina
38. ”, 25, 15000)
= Teacher{"Mrs. Shrividya', 40, 30000)
$= Student('Swaroop’, 25, 75)
60. members = [t, s]
for member in members:
member.tell()
Programming Test