PFP191FE

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

1. What will be the value of x when the following statement is executed: x = int(98.

6)
A. 100
B. 6
C. 98
D. 99
2. What is a correct syntax to output “Hello World” in Python?
A. print(“Hello World”)
B. echo”Hello World
C. p(“Hello World”)
D. echo(“Hello World”);
3. How do you create a variable x with the numeric value 5?
A. x = 5
B. Both the answer are correct
C. x = int(5)
D. Both the answer are incorrect
4. Which of these statements is used to indicate that class A will inherit all features of class
B?
1. class A extends B:
2. A = B++;
3. class A inherit B:
4. classA(B)
5. When reading a file using the file object, what method best for reading the entire file into a single
string ?
A. readlines()
B. read_file_to_str()
C. read()
D. readline()
6. What would the following mean in regular expression? [ a-z, 0-9 ]
A. Match an entire line as long as it is lowercase letters of digit
B. Match a lowercase letter or a digit.
C. Match any number of lowercase letters followed by any number of digits.
D. Match any text that is surrounded by square braces.
7. How do you start writing an if statement in Python ?
A. If( x > y )
B. If x > y then :
C. x > y?:
D. if x > y:
8. When you have a multiple lines in a block, how do you indicate the end of the if block ?
A. You de-indent the next line past the if block to the same level of indent as the original if
statement.
B. You use a curly brace { after the last line of the if block.
C. You admit the semicolon : on the last line of the if block.
D. You put in the colon : character on a line by itself to indicate we are done with the if block.
9. What does the __init__() the function do in Python?
A. Initializes the class for use.
B. This function is called when a new object is instantiated:
C. Initializes all the data attributes to zero when called.
D. None of the above
10. Which of the following is a comment in Python ?
A. // This is a test
B. # This is a test
C. $ This is a test
D. /” This is a test */
11. Which of these collections defines a DICTIONARY ?
A. [“apple”,”banana”,”cherry”]
B. (“apple”,”banana”,”cherry”)
C. {“apple”,”banana”,”cherry”}
D. {“name”:”apple”,”color”:”green”}
12. What does the following Python code print out ?
a = [1,2,3,8]
b = [4,5,6]
c=a+b
print(c)
A. [1,2,3,8,4,5,6]
B. 7
C. It raises an exception
D. 28
13. What the most common Unicode encoding when moving data between systems ?
A. UTF-64
B. UTF-32
C. UTF-128
D. UTF-8
14. What does the following code print out ?
Print(“123” + “ abc” )
A. 123+abc
B. Hello world
C. 123abc
D. This is a syntax error because you cannot add string.
15. Which of the following not define the set { ‘a’,’b’,’c’ }:
A. s = set([‘a’,’b’,’c’])
B. s = {(‘a’,’b’,’c’)}
C. s = set(‘a’,’b’,’c’)
D. s = {‘a’,’b’,’c’}
16. Which data structure is being out to use in the code given below?
# Code starts
org = ‘QuizOrbit’
count = {}
for i in org :
if i in count :
count[i] += 1
else :
count[i] = 1
print(count)
# Code Ends
A. tuple
B. list
C. string
D. dictionary
17. Which of the following will result in an error ?
A. Both (b) and (c)
B. print(str1[0:9])
C. print(str1[2])
D. str1[1] = “x”

18. What will be the value of x when the following statement is executed : X = round(98.6).
A. 98
B. 99
C. 6
D. 100
19. One again consider this dictionary :
d = {‘foo’:100,’bar’:200,’baz’:300}
What is the result of this statement :
d[‘bar’:’baz’]
A. [200,300]
B. (200,300)
C. 200 300
D. It raises an exception
20. Assume the variable x has been initialized to an integer value (e.g,x = 3). What does
the following statement do ?
x=x+2
A. Create a function called “x” and put the value 2 in the function
B. Produce the value “false” because “x” can never equal “x+2”
C. This would fail as it is a syntax error
D. Retrieve the current value for x, add two to it and put
21. At the moment of creation of a new project, Python looks at the _____ definition to define the
structure and capabilities of the class.
A. Class
B. Method
C. Cache
D. Instance
E. Constructure
22. What will the following Python code print out ?
friends = [‘Joseph’,’Glenn’,’Sally’]
friends.sort()
print(friends[0])
A. Joseph
B. Sally
C. Friends
D. Glenn
23. Find the output of the code given below?
# Code starts
content = (21,26,37,94)
content.append((75,62,79))
print(len(content))
# Code Ends
A. 1
B. 2
C. 7
D. Error
24.
class Person:
def__init__(self,name,age):
self.name = name
self.age = age
The correct way to instantiate the above Person class is :
A. Person.create(“Rufus”, 3)
B. Person(“Rufus”, 3)
C. Person()
D. Person.init(“Rufus”.3)
25. Which operator can be used to compare two values ?
A. =
B. <>
C. ==
D. ><
26. What will the following code print out ?
x=0
if x < 2 :
print(“Small”)
elif x < 10 :
print(“LARGE”)
print(“All done”)
A. Small Medium LARGE All done
B. Small All done
C. Small
D. LARGE All done
27. True or False? In order to extend a class, the new class should have access to all the data and
inner workings of the parent class.
A. False
B. True
28. Which of the following functions do you use to write data in the binary format ?
A. send
B. dump
C. write
D. output
29. What do we use the second parameter of the open() call to indicate :
A. how large we expect the file to be
B. the list of folders to be searched to find the file we want to open
C. what disk drive the file is stored on
D. whether we want to read data from the file or write to the file
30. For the following code, which of the following statements is true ?
def printHello()
print(“Hell0”)
a = printHello()
A. Both printHello() and a refer to the same object
B. printHello() is a function and a is a variable. None of them are objects.
C. printHello() and a refer to different objects.
D. Syntax error! You cannot assign function to
31. What is the correct syntax to output the type of a variable or object in Python ?
A. print(typeof(x))
B. print(typeofx)
C. print(typeOf(x))
D. print(type(x))
32. Which the following statement assigns the value 100 to the variable x in Python:
A. x = 100
B. x == 100
C. let x = 100
D. x := 100
E. x << 100
33. What will the following Python code print out ?
friends = [‘Joseph’,’Glenn’,’Sally’]
friends.sort()
print friends[1]
A. Joseph
B. Sally
C. Friends
D. Glenn
34. Python strings have a property called “immutability”. What does this mean ?
A. Strings in Python can be represented as arrays of chars
B. Strings in Python can’t be changed
C. Strings can’t be divided by numbers
D. You can update a string in Python with concatenation.
35. What do we do to a Python statement that is immediately after an if statement to indicate that
the statement is to be executed only when the if statement is true ?
A. Underline all of the conditional code
B. Begin the statement with a curly brace {
C. Start the statement with a “#” character
D. Indent the line below the if statement
36. Which method can be used to return a string in lower case letter ?
A. lower.Case()
B. lower()
C. toLower()
D. lowercase()
37. Which of these collections defines a SET ?
A. (“apple”,”banana”,”cherry”)
B. [“apple”,”banana”,”cherry”]
C. {“apple”,”banana”,”cherry”}
D. {“name”:“apple”,”color”:”green”}
38. What is the best way to think about a “SyntaxError” while programming?
A. The computer did not understand the statement that you entered
B. The comouter needs to have its software upgraded
C. The computer is overheating and just wants you to stop to let it cool down
D. The computer has used GPS to find
39. 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 ?
From : hello@gmail.com
From : hi@fpt.edu.vn
From : hello@fpt.edu.vn
….
A. rstrip()
B. split()
C. startswith()
D. find()
40. What will be the output of the following Python code ?
f = None
for i in range(5):
with open(“data.txt”,”w”) as f :
if i > 2 :
break
print(f.closed)
A. True
B. False
C. None
D. Error
41. 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 you could print out your own message
a bad file name was entered ?
fname = raw_input(“Enter the file name : “)
fhand = open(fname)
A. signal handlers
B. on error resume next
C. try / except
D. try / catch / finally
42. What is the purpose of the following Python code ?
fhand = open(‘mbox.txt’)
x=0
for line in fhand:
x=x+1
print x
A. Reverse the order of the lines in mbox.txt
B. Count the line in the file ‘mbox.txt’
C. Remove the leading and trailing spaces from each line in mbox.txt
D. Convert the line in mbox.txt to upper case
43. Object and class attributes are accessed using ___ notation in Python.
A. Dot notation
B. Arrow notation
C. Plus notation
D. And notation
44. What is a correct syntax to return the third character in a string ?
A. x = sub(“Hello”,0,2)
B. x = “Hello”[2]
C. x = “Hello”.sub(0,2)
D. x = sub”Hello”
45. Which of the following statement is not true about object-oriented programming ?
A. One of the benefits of object-oriented programming is that it can hide complexity
B. A powerful feature of object-oriented programming if the ability to create a new class by extending an
existing class
C. Constructor methods are required to initialize an object and destructor methods are required to
destroy the object when no longer required
D. A class contains functions as well as the data that is used by those functions.
46.
class Pokemon():
def__init__(self, name, type):
self.name = name
self.type = type
def stringPokemon(self):
print(f“Pokemon name is {self.name} and type is {self.type}”)
class GrassType(Pokemon):
# overrides the stringPokemon() function on ‘Pokemon’ class
def stringPokemon(self):
print(f”Grass type pokemon name is {self.name}”)
poke1 = GrassType(‘Bubasaur’,Grass)
poke1.stringPokemon
poke1.stringPokemon()
poke2 = Pokemon(‘Charizard’, Fire)
poke2.stringPokemon
poke2. stringPokemon()
A. Error because the extending class has a stringPokemon() function which already exists.
B. Grass type pokemon name is Bulbasaur Grass type pokemon name is Charizard
C. Grass type pokemon name is Bulbasaur Pokemon name is Charizard and type is fire.
D. Pokemon name is Bulbasaur and type is Grass Pokemon name is Charizard and type is fire.
47. Find the output of the given Python program
a = 25
if a < 15:
print(“Hi”)
if a <= 30:
print(“Hello”)
else:
print(“Know Program”)
A. Hi Hello
B. Hello
C. Hi Know Program
D. Hi
48.What is the output of the code?
try:
list = 5*[0]+5*[10]
x = list[9]
print("Done!")
except Index Error:
print("Index out of Bond! *)
else:
print("Nothing is wrong!")
finally:
print("Finally block!”) t = [9, 41, 12, 3, 74, 15)
A. ‘Nothing is wrong!’ followed by ‘Finally block!’
B. ‘Finally block!’
C. ‘Done!’ follow by ‘Nothing is wrong!’ followed by ‘Finally block!’
D. ‘Done!’ follow by ‘Nothing is wrong!’
49.For the following code
x=1
If x < 2
print(‘Below 2’)
elif x >= 2:
print(‘Two or more’)
else:
print(‘Something else’)
What is the output?
A. x = -2.0
B. This code will never print ‘Something else’ regardless of the value for ‘x’
C. x = 2.0
D. It will print out “Below 2”
50.What is output of the sample code?
class A:
def _init_(selt)
self.calel(30)
def calel(seff, i)
self=2*i
class B(A):
def _ init__(self)
super(),_init_()
print(" from Bis", selfi)
def calel(self, i)
self.i=3* i;
b=B()
A. The __init__ method of class A gets invoked and it displays i from B is 60
B. The __init__ method of only class B gets invoked.
C. The __init_ method of class A gets invoked and it displays i from B is 0”
D. The __init__method of class A gets invoked and it displays i from B is 90”
51. class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
class JackRussellTerrier(Dog):
pass
class Dachshund(Dog):
pass
class Bulldog(Dog):
pass
miles = jackRussellTerrier(“Miles”,4)
buddy = Dachshund(“Buddy”,9)
jack = Bulldog(“Jack”,3)
jim = Bulldog(“Jim”,5)
Given the above code snippet, which of the following REPL outputs are correct? (select all
that apply)
A isinstance(jack, Dog)
B. isinstance(miles, Dog)
C. isinstance(jack, Dachshund)
D. isinstance(miles, Bulldog)
52. What does the Python dir() function show when we pass an object into it as a parameter?
A. It shows the parent class
B. It shows the number of parameters to the constructor
C. It shows the methods, and attributes of the object
D. It shows the type of the object
53. Which of these words is a reserved word in Python?
A. while
B. payroll
C. names
D pizza
54. Which came first, the instance or the class?
A. Class
B. Function
C Instance
D. Method
55. A list of lines is returned if using the method of
A <readable()>
B. <readnines()>
C <readlines()>
D <readline()>
56. What is the output of the following python code snippet?
#Code starts
emp1 = (Ajay 25,10000)
emp2 = (Sidhi 23,15000)
emp1[2] = 20000
print(emp1[2]+emp2[2])
# Code Ends
A 35000
B 25000
C. Type Error
D. None of the above.
57. To read the entire remaining contents of the file as a string from a file object infile, we use?
A infile.read(2)
B. infile.read()
C infile.readline()
D. infile readlines()
58. You look at the following text: 6:
if x== 6:
print('Is 6')
print('Is Still 6')
print('Third 6')
It looks perfect but Python is giving you an 'Indentation Error' on the second print statement.
What is the most likely reason?
A. In order to make humans feel inadequate, Python randomly emits 'Indentation Errors' on perfectly
good code - after about an hour the error will just go away without any changes to your program
B. Python has reached its limit on the largest Python program that can be run
C. Python thinks 'Still' is a mis-spelled word in the string
D You have mixed tabs and spaces in the file
59. Which of the following does not correctly create an object instance?
A. puppy = Dog("Jamie")
B. dog = Dog("Jamie")
C. jamie = Dog()
D. pupper = new Dog("Jamie")
60. List a is defined as follows:
a = [1, 2, 3, 4, 5]
Select all of the following statements that remove the middle element 3 from a so that it equals [1, 2,
4, 5]
A. a[2 : 2] =[]
B. a[2] =[]
C. del a[2]
D. a.remove(3)
61. Which collection is ordered, changeable, and allows duplicate members?
A. SET
B. DICTIONARY
C. TUPLE
D. LIST
62. If we open a file as follows:
xfile = open('mbox.txt')
What statement would we use to read the file one line at a time?
A. for line in xfile:
B. while (getline (xfile, line)) {
C. READ xfile INTO LINE
D. READ (xfile," END=10) line
63. Which of the parts of a computer actually executes the program instructions?
A. RAM
B CPU
C. Input/Output Devices
D Secondary Memory
64. Consider this assignment statement
a, b, c = (1, 2, 3, 4, 5, 6, 7, 8, 9)[1::3]
Following execution of this statement, what is the value of b
A. 2
B. 4
C. 5
D. 6
65. When Python is running in the interactive mode and displaying the chevron prompt (>>>) -
what question is Python asking you?
A. What Python script would you like me to run?
B. What is the next machine language instruction to run?
C. What is your favorite color?
D. What Python statement would you like me to run?
66. For the following code:
astr= 'Hello Bob'
istr = 0
try:
istr = int(astr)
except:
istr=-1
What will the value be for istr after this code executes?
A -1
B. It will be the 'Not a number' value (ie. NaN)
C. It will be a random number depending on the operating system the program runs on
D false
67. Which method can be used to return a string in upper case letters?
A. upper()
B. uppercase()
C. toUpperCase()
D. upperCase()
68. Which of the following are valid ways to specify the string literal foo'bar in Python:
A. "foo’bar"
B. ‘foo"bar’
C. “””foo'bar”””
D. 'foo'bar'
69. What relationship is suited for Course and Faculty?
A. Association
B. Composition
C. Inheritance
D. All of the above
70. What relationship correctly fits for University and Professor ?
A. Composition
B. Inheritance
C. Association
D. All of the above
71. What is the output of print list[1:3] if list = [ 'abcd', 786, 2.23,'john', 70.2 ]?
A. ['abcd', 786, 2.23, 'john', 70.2]
B. abcd
C. [786, 2.23]
D. None of the above
72. A USB memory stick is an example of which of the following components of computer
architecture?
A. Central Processing Unit
B. Main Memory
C. Secondary Memory
D. None of these
73. What is the value of the following expression ?
45 % 10
A. 4
B. 2
C. 5
D. 0.42
74. What will be the value of x after the following statement executes x=1+2*3-8/4
A. 3.0
B. 15
C. 4
D. 5.0
75. Given a code,
class People():
def init (self, name):
self.name = name
def namePrint(self):
print(self.name)
person1 = People("Sally")
person2 = People("Louise"))
person1.namePrint()
What is correct answer?
A. person1 and person2 are two different instances of the People class
B. The __init__ method is used to set initial values for attributes.
C. 'self is not needed in def namePrint(self)
D. person2 has a different value for 'name' than person!
76. How do you start writing an if statement in Python?
A. if x>y:
B. if (xy)
C. if x>y then;
D. x>y?
77. Which of these collections defines a TUPLE?
A. ["apple", "banana", "cherry"]
B. ("apple", "banana", "cherry"}
C. ("name", "apple", "color": "green"}
D. ("apple", "banana", "cherry")
78. Which method can be used to replace parts of a string?
A. replace()
B. replaceString()
C. repl()
D. rep()
79. What will be the value of x after the following statement executes: x=2*3-8/4%2
A. 1
B. 2
C. 4
D. 6
80. Which of the following variables is the "most mnemonic"?
A. x1q3z9ocd
B. var_173
C. xyz
D. days
81. Which of the following statements is True?
A. You can only make a single object from the given class.
B. A class is blueprint for the object.
C. Neither statement is true.
D. Both statements are true.
82. What is the correct way to create a function in Python?
A. create function(){}
B. function(){}
C. def function()
D. define function(){}
E. def function():
83. What is the output from this print() function call:
print(
'$100 $200 $300'.count(‘$’),
'$100 $200 $300'.count(‘$’, 5, 10),
’$100 $200 $300’.count(‘$’, 5))
A. 310
B. 311
C. 312
D. 321
84. How would you express the constant floating-point value 3.2x10^3 in Python?
A 32e-3
B. 3.263
c. 0.32
D. 3.2e3
85. In the following code, print(98.6) What is “98.6” ?
A A variable
B. A constant / literals
C. A parameter
D. A pointer
86. In the following code, x = 9 What is x?
A. A constant
B.A parameter
C. A variable
D. A pointer
87. What keyword is used to indicate the start of a method in a Python class?
A. break
B. continue
C. def
D. function
88. Which of the following reserved keyword is used to end a function, return generator?
A. retum
B. switch
C. yield
D. break
89. What is the output of the following code?
class Foo:
def printLine(self, line = ‘Python’):
print(line)
o1 = Foo()
o1.printLine(‘Java’)
A Line
B. Java n\ Python
C. Python
D. Java
90. .Which of the following statement about Python is not correct?
A.Due to its proprietary nature database access from python is not available for many database
B.Python is a popular scripting language for connecting and accessing databases
C.The python ecosystem is very rich and provides easy to use tools for data science
D.There are libraries and APIs available to access many of the popular databases from python
91. Suppose you are given a set(s1={1,2,3}) then what is the output for the code —
2*s1?
A. (1.1.2.2.3.3)
B. (1.1.22.33]
C. (1,2,3,1,2,3)
D. Illegal
92. Which of the following statements assigns the value 100 to the variable x in Python:
A. x = 100
B. x := 100
C. let x= 100
D.x == 100
E.x << 100
93.identify the data structure we use in the code given below?
# Code starts
asthetic1 = ‘quizOrbit’
asthetic2 = ‘QuizOrbit’
print(asthetic1!=asthetic2)
# Code Ends
A. Tree
B. True
C. Dictionary
D. HashMap
94.What Python function would you use if you wanted to prompt the user for a file name to open ?
A. input()
B. read()
C. cin
D. file_input()
95.What is the Python reserved word that we use in two-way if tests to indicate the block of code ….
executed if the logical test is false?
A. break
B. switch
C. toggle
D. else
96. How do you insert something on a new line in a file?
A. type the content on the line below
B. You cannot do this
C. \n
D. write.newline(‘x’)
97: Which of the following is the correct way to define an initializer method?
A. def __init__(self, title, author):
B. __ init__(self, title, author):
C. det _init_():
D. def__init_(title, author:
Câu 98.What is the "wild card" character in a regular expression ((¢., the character that matches
any character)?
A. ?
B. $
C. *
D. .
99 .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
C. Itenables random movement throughout the file
D. It allows us to open more than one files and read them in a synchronized
manner
100. Which method can be used to remove any whitespace from both the beginning and the end ?
A. trim()
B. ptrim()
C. ltrim()
D. strip()
101. The readlines() method returns
A str
B. a list of lines
C. a list of single characters
D. a list of integers
102. Predict the output of the code given below?
collection1 = (‘QuizOrbit’, ‘Meha', 26, ‘India’)
collection2 = (‘QuizOrbit’, ‘Divika’, 23, ‘Inda’)
print(collection1 > collection2)
#Code Ends
A True
B. False
C. None of These
D. Error
103. What would the following Python code print out?
stuff = dict()
print(stuff[ ‘candy’])
A-1
B. 0
C. The program would fail with a traceback
D. candy
104. Which of the following statements is not true about object-oriented programming?
A. One of the benefits of object-oriented programming is that it can hide complexity
B. A class contains functions as well as the data that is used by those functions
C. Constructor methods are required to initialize an object and destructor methods are
required to destroy the object when no longer required
D. A powerful feature of object-oriented programming is the ability to create a new class by
existing class
105. What's the output of the following code snippet?
>>> class Dog
def walk(self) return "walking"
def speak(self) return "Woof!"
>>>class JackRussell Temer(Dog)
def speak(self): return "Arff"
>>> bobo = Jack RussellTerner()
>>> bobo.walk()
A. Ari
B. walking
C. AttributeError JackRussell Temer object has no attribute walk
D. Woof
106. What is the output of the following code?
class Point
def_init_(self, x=0,y=0):
sell x=x+1
selly-y+1
p1=Point print(p1x, p1.y)
A. Initializes the class for use.
B. 00
C. 11
D. None None
E. Xy
107. Which of these collections defines a LIST ?
A. (“apple”,”banana”,”cherry”)
B. [“apple”,”banana”,”cherry”]
C. {“apple”,”banana”,”cherry”}
D. {“name”:“apple”,”color”:”green”}
108. What extension must you add to the end of a file when saving?
A. py
B. ppt
C. pynb
D. bxt
109. Which of the following is NOT a good synonym for "class" in Python?
A. direction
B. blueprint
C. pattern
D. template
110. Whenever possible, what is the recommended way to ensure that a file object is properly
closed after usage?
A. It doesn't matter
B. By using the with statement
C. By using the try/finally block
D. Making sure that you use the close() method before the end of the script
111. 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
B. Tums the text in the file into a graphic image like a PNG or JPG
C. Reads the entire file into the variable inp as a string
D. Prompts the user for a file name
112. What is the Python reserved word that we use in two-way tests to indicate the block of code
that to be executed if the logical test is false?
A break
B switch
C else
D. toggle
113. Which of the following can be used to invoke the_int_method in B from A where A is a
subclass of B?
A super()_ int_ ()
B. super() _int_(self)
C B_int_()
114. What is the proper way to say "good-bye" to Python?
A. quit()
B. stop()
C. ext()
D. end()
115. Which method can be used to return a string in lower case letters?
A. toLower()
B. lower()
C. lowercase()
D. lowerCase()
116. What are the names of the two types of mode that are used in Python?
A. Interactive mode & Script mode
B. Interactive mode & Imperial mode
C. Interactive mode & Scratch mode
D. Imperial mode & Script mode
117. For the following code
astr=64
istr=5
Try:
istr=str(astr)
except:
What will the value be for istr after this code executes?
A -1
B. It will be the Not a number value (ie NaN)
C. It will be a random number depending on the operating system the program runs on
D. 64
118. What is the output for “Tutorials Point” [100:200]?
A Index error
B ‘’
C. Tutorials Point
D. Syntax error
119. What will the following program print out
>>>x = 15
>>>x = x + 10
>>> print(x)
A 25
B.5
C 15
D. 'print x’
120. For the following list, how would you print out Saly?
friends=['Joseph’, ‘Glenn’, 'Saly’]
A print friends[3]
B. print(friends [Sally]
C. print(friends[2])
D. print(thends[2:11)
121. You have the following dictionary definition
d=(“foo” :100, “bar”: 200, "baz": 300)
What method call will delete the entry whose value is 200?
A d.pop("bar")
B. d.dremove(bar)
C. d.dremove(2007)
D. d.pop(2007)
122. Which of the following commands can be used to read the next line in a file using the file object
empties?
A. tmpfile.read(n)
B. tmpfie.read()
C. tmpfile.readine()
D. tmpfile.readlines()
123. Which of the following is not a Python reserved word?
A. iterate
B. continue
C. else
D. break
124. Which of the following elements of a mathematical expression in Python is evaluated last?
A. Addition
B. Multiplication
C. Parentheses
D. Division
125. Which of the following slicing operations will produce the list [12, 3]
t=[9,41, 12, 3, 74, 15]
A. t[1:3]
B. t[12:2]
C. t[:]
D. t [2:4]
126. What is true about the following code segment
If x==5
print('is 5)
print(“ is Still 5)
print("Third 5)
A Depending on the value of x, either all three of the print statements will execute or none of the
statements will execute
B. The string is 5' will always print out regardless of the value for x
C. The string is 5 will never print out regardless of the value for x
D. Only two of the three print statements will print out of the value of x is less than zero
127. Given the file dog_breeds bot, which of the following is the correct way to open the file for
reading as a find file?
Select all that apply
A open('dog_breeds.txt”, wb)
B open('dog_breeds.txt”, 'rb')
C. open('dog_breeds.txt”, “r”)
D open(“ dog_breeds br”, w)
128. Which of the following is not a method of opening files?
A. Replace
B. Append
C Read
D. Write
129. Which of the following elements of a mathematical expression in Python is evaluated
first?
A. Addition +
B. Multiplication *
C. Subtraction -
D. Parentheses ()
130.
class Sales
del_int_(self, id)
self id=id
id=100
val = Sales(123)
print (val.id)
A. SyntaxError, this program will not run
B. 100
C. 123
D. None of the above
131. What is the correct syntax to return the first character in a string?
A. x = “Hello”.sub(0,1)
B. x = “Hello”[1]
C. x = “Hello”[0]
D. x = sub(“Hello”, 0, 1)
132. Which of the following data structures in python are immutable?
A. Linked List
B. Tree
C. Tuple
D. All of the above
133. You want to create a bytes object consisting of five null (0x00) bytes. Choose all the apply.
A. bytes(5)
B. bytes(0, 0, 0, 0, 0)
C. bytes(‘\x00\x00\x00\x00\x00’, ‘utf-8’)
D. bytes([0] * 5)
134. What does the Python input() function do?
A. Pause the program and read data from the user
B. Connect to the network and retrieve a web page.
C. Read the memory of the running program
D. Take a screen shot from an area of the screen
135. What is "self” typically used for in a Python method within a class?
A. To terminate a loop
B. To set the residual value in an expression where the method is used
C. The number of parameters to the method
D. To refer to the instance in which the method is being called
136. What is the output of print list if list = [‘abed’, 786 , 2.23, ‘john’, 70.2]?
A. [‘abed’, 786 , 2.23, ‘john’, 70.2]
B. list
C. Error
D. None of the above
137. You want to create a bytes object consisting of five null (0x00) bytes. All of the following will
work except one. Select the one that doesn't work:
A. bytes(5)
B. bytes(0, 0, 0, 0,0)
C. bytes("\x00\x00\x00\x00\x00", ‘utt-8’)
D. bytes([0] * 5)
138. Given the following line of text:
From Stephen. marquard@uct ac.za Sat Jan 5 09:14:16 2008
What would the regular expression '\S+?@\S+' match?
A. \@\
B. From
C. marquard@uet
D. stephen. marquard@uct.ac.za
139.For the following code
If x < 2
print(‘Below 2’)
elif x >= 2:
print(‘Two or more’)
else:
print(‘Something else’)
What is the output?
A. x = -2.0
B. This code will never print ‘Something else’ regardless of the value for ‘x’
C. x = 2.0
D. x = -22
140. What is the incorrect ways to create a function in Python? (Choose all the apply.)
(Choose 3 Answers)
A. create myFunction():
B. def myFunction():
C. func myfunction():
D. def function myfunction():
142. What is the output of the following code?
class Point
def__init__(self, x = 0, y = 0):
self.x = x
selt.y = y
def __sub__(self, other)
x= self.x + other.x
y = self.y + other.y
return Point(x,y)
p1 = Point(3, 4)
p2= Point(1,2)
result = p1-p2
print(result.x, result.y)
A. 2 2
B. 4 6
C. 0 0
D. 1 1
143. What is the difference between the "+" and "*" character in regular expressions?
A. The "+" matches upper case characters and the "*" matches lowercase characters
B. The "+" matches the beginning of a line and the "*" matches the end of a line
C. The "+" matches the actual plus character and the "*" matches any character
D. The "+" matches at least one character and the "*" matches zero or more characters
145. How do you start writing a while loop in Python?
A. while (x > y)
B. while x > y {
C. while x > y:
D. x > y while {
146. Which statement is used to stop a loop?
A. exit
B. break
C. stop
D. return
147. Which of the following is rarely used in Object Oriented Programming?
A. Method
B. Constructor
C. Attribute
D. Destructor
148. Python scripts (files) have names that end with:
A. exe
B. py
C. png
D. doc
149. What is the result of this statement?
print(ord(‘foo’))
A. 102
B. It raises an exception
C. 102111111
D. 324
150. Which collection does not allow duplicate members?
A. SET
B. DICTIONARY
C. TUPLE
D. LIST
151. What is the name of this symbol (>>>)?
A. Chevrons
B. Hash tags
C. Colon
D. Semi Colon
152. Assume x and y are assigned as follows:
x=5
y = -5
What is the effect of this statement:
x, y = (y, x)[::-1]
A. The values of x and y are unchanged
B. Both x and y are -5
C. Both x and y are 5
D. The values of x and y are swapped
153. Which of the following code uses the inheritance feature of Python?
A. Class Foo: Pass
B. Class Foo(object): pass class Hoo(object): pass
C. Class Foo: pass class Hoo(Foo): pass
D. None of the above code.
154. What does the following Python sequence print out?
x = ‘From: Using the : character’
y = re.findall('^F.+:', x)
Print(y)
A. ^F.+.:
B. ['From: Using the:’]
C. [‘From:’]
D. From:
155. How do you start writing a for loop in Python?
A. for x = 1 to y:
B. for x > y:
C. for each x in y:
D. for x in y:
156. In Python, a class is .... for a concrete object.
A. nuisance
B. instance
C. blueprint
D. distraction
157. If you a class is derived from two different classes, is called __
A. Multilevel Inheritance
B. Multiple Inheritance
C. Hierarchical Inheritance
D. Python Inheritance
158. You have the following dictionary definition:
d={‘foo’: 100, ‘bar’: 200, ‘baz’: 300}
What method call will delete the entry whose value is 300?
A. d.pop("baz")
B. d.remove("bar")
C. d.remove("200")
D. d.pop("200")
159. What does the following Python code print out ?
a = [1,2,3]
b = [4,5,6]
c=a+b
print len(c)
A. [4, 5, 6]
B. 15
C. 21
D. 6
160. A bytes object is immutable. If you want a binary sequence that can be modified, you should
use a bytearray. Is it possible to create a bytearray object directly from a bytes object, as shown
below:
array_of_bytes = bytearray(b’15\x80a#’)
A. Yes
B. No
161. How would you use string slicing [:] to print out ‘uct’ from the following string?
x= 'From marquard@uct ac.za’
A. print(x[14/17])
B. print(x[14:17])
C. print(x[14:3])
D. print(x[14+3])
161. The ____ keyword defines a template indicating the data that will be in an object of the class
and the functions that can be called on an object of the class.
A. Class
B. object
C. class
D. instance
162. What is the value of the following expression?
42 % 10
A. 2
B. 420
C. 4210
D. 42
163. What is the iteration variable in the following Python code?
for letter in ‘banana’ :
print(letter)
A. ‘banana’
B. for
C. letter
D. print
164. In which of the following does the CricketFan class correctly inherit from the PartyAnimal
class?
A. from party import PartyAnimal
B. class CricketFan(PartyAnimal)
C. an = PartyAnimal()
D. CricketFan = PartyAnimal()
165. In the following code (numbers added) - which will be the last line to execute successfully?
(1) astr = ‘Hello Bob’
(2) istr = int(astr)
(3) print(First’,istr)
(4) astr ='123'
(5) istr = int(astr)
(6) print('Second,, istr)
A.2
B.1
C.6
D.3
166. What is the result of the following statement:
list((b'abcde' + 'fghi’)[3:6))
A. [b’d, b’e’, b’f]
B. b’def’
C. [100, 101, 102]
D. It Raises an exception
167. What is the type of the return value of the re-findall() method?
A. A list of strings
B. An integer
C. A boolean
D. A Single character
168. in Object Oriented Programming, what is another name for the “attributes” of an object
A. forms
B. methods
C. portions
D. messages
E. fields
169. Which of the following data structures in python are immutable?
A. Linked List
B. Tree
C. String
D. All of the above
170. Which of the following is the way we match the "start of a line” in a regular expression?
A. ^
B. str.startswith()
C. \linestart
D. String.startsWith()
171. The Python Enhancement Proposal (PEP) that enumerates stylistic guidelines for Python code
is known as ….
A. PEP 8000
B. PEP 20
C. PEP 8
D. PEP 257
172. Which of these operators is not a comparison / logical operator?
A. =
B. >=
C. ==
D. >
E. <
173. What is output for:
b= [11,13,15,17,19,21]
print(b[::2])
A. [19,21]
B. [11,15]
C. [11,15,19]
D. [13,17,21]
174. Which of the following represents a distinctly identifiable entity in the real world?
A. A class
B. An object
C. A method
D. A data field
175. Which of the following represents a template, blueprint, or contract that defines objects of the
same type?
A. A class
B. An object
C. A method
D. A data field
176. Which of the following keywords mark the beginning of the class definition?
A. def
B. return
C. class
D. All of the above.
177. Which of the following is required to create a new instance of the class?
A. A constructor
B. A class
C. A value-returning method
D. A None method
178. Which of the following statements is correct?
A. A reference variable is an object.
B. A reference variable refers to an object.
C. An object may contain other objects.
D. An object can contain references to other objects.
179. What relationship is best suited for Employee and Person?
A. association
B. composition
C. inheritance
D. None of the above
180. What relationship is best suited for House and Door?
A. association
B. composition
C. inheritance
D. All of the above
181. What relationship is appropriate for Fruit and Papaya?
A. association
B. composition
C. inheritance
D. All of the above
182. ____ is not a keyword, but by convention it is used to refer to the current instance (object) of a
class.
A. class
B. def
C. self
D. init
183. Which of the following best describes "Regular Expressions"?
A. A small programming language unto itself
B. A way to solve Algebra formulas for the unknown value
C. The way Python handles and recovers from errors that would otherwise cause a traceback
D. A way to calculate mathematical values paying attention to operator precedence
184. What does the '[0-9]+' match in a regular expression?
A. Several digits followed by a plus sign
B. Any mathematical expression
C. One or more digits
D. Zero or more digits
E. Any number of digits at the beginning of a line
183. What does the following Python program print out?
x = ‘40’
y = int(x) +2
print(y)
A. int402
B. 402
C. 42
D. x2
184. How are Python dictionaries different from Python lists?
A. Python lists are indexed using integers and dictionaries can use strings as indexes
B. Python dictionaries are a collection and lists are not a collection
C. Python lists can store strings and dictionaries can only store words
D. Python lists store multiple values and dictionaries store a single value
185. What is the iteration variable in the following Python code:
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print('Happy New Year:', friend)
print('Done!')
A. friend
B. Glenn
C. Sally
D. friends
186. Which reserved word indicates the start of an "indefinite" loop in Python?
A. def
B. while
C. indef
D. break
E. for
187. What does the following Python code print out?
print(len('banana')*7)
A. 42
B. banana7
C. bananabananabananabananabananabananabanana
D. 0
188. (T/F) When you add items to a dictionary they remain in the order in which you added them.
A. False
B. True

You might also like