Python MCQs
Python MCQs
MCQs.
a FREE book packed with
valuable multiple-choice
questions
@datascience-trainer
Question #1: what does the following code do?
description: The 'def' statement defines a function. The 'pass' statement is a null operation.
print type(1/2)
<type 'int'> - correct
<type 'number'>
<type 'float'>
<type 'double'>
<type 'tuple'>
description: division of an integer by another integer yields an integer in version 2.x of
python
@datascience-trainer
<type 'type'>
description: The argument to the type() call is a return value of a function call, which returns
None
print type(1J)
<type 'complex'> - correct
<type 'unicode'>
<type 'int'>
<type 'float'>
<type 'dict'>
description: An imaginary literal yields a complex number with a real part of 0.0
a = [1,2,3,None,(),[],]
print len(a)
syntax error
4
5
6 - correct
7
description: The trailing comma in the list is ignored, the rest are legitimate values
@datascience-trainer
<type 'number'>
<type 'float'> - correct
<type 'double'>
<type 'tuple'>
description: division of an integer by another integer yelds a float in version 3.x of python.
Also note there is a changed print syntax in python 3.
d = lambda p: p * 2
t = lambda p: p * 3
x = 2
x = d(x)
x = t(x)
x = d(x)
print x
7
12
24 - correct
36
48
description: start with 2, multiply by 2, multiply by 3, multipy by 2.
x = 4.5
y = 2
print x//y
2.0 - correct
2.25
9.0
20.25
21
description: this is truncating division. The remainder is dropped.
nums = set([1,1,2,3,3,3,4])
print len(nums)
1
2
4 - correct
@datascience-trainer
5
7
description: nums is a set, so only unique values are retained.
x = True
y = False
z = False
if x or y and z:
print "yes"
else:
print "no"
yes - correct
no
fails to compile
description: AND is higher precedence than OR in python and is evaluated first
x = True
y = False
z = False
if not x or y:
print 1
elif not x or not y and z:
print 2
elif not x or y or not y and x:
print 3
else:
print 4
1
2
3-
correct
4
description:
NOT has first precedence, then AND, then OR
A) PYTHONPATH directory
B) current directory
C) home directory
@datascience-trainer
D) installation dependent default path
A only
A and D
A, B, and C
A, B, and D - correct
A, B, C, and D
description: First is the current directory, then is the PYTHONPATH directory if set, then is the
installation dependent default path
Question #15: In python 2.6 or earlier, the code will print error type 1 if
accessSecureSystem raises an exception of either AccessError type or
SecurityError type
try:
accessSecureSystem()
except AccessError, SecurityError:
print "error type 1"
continueWork()
true
false - correct
description: The except statement will only catch exceptions of type AccessError and name
the exception object SecurityError. In order to catch both you can use a tuple like this: except
(AccessError, SecurityError). Python has been changed in version 3.0 so that the syntax
shown in the question will actually catch both types.
Question #16: The following code will successfully print the days and then the months
daysOfWeek = ['Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday']
months = ['Jan', \
'Feb', \
'Mar', \
'Apr', \
'May', \
'Jun', \
'Jul', \
'Aug', \
'Sep', \
'Oct', \
'Nov', \
'Dec']
print "DAYS: %s, MONTHS %s" %
(daysOfWeek, months)
true
false - correct
description: daysOfWeek is ok because expressions in parentheses, square brackets or curly
braces can be split over more than one physical line without using backslashes. months is ok
because backslashes are used to join physical lines, even though they are not required in this
case. The print statement will not print the data because 2 logical lines are used without a
backslash to join them into a logical line.
f = None
True - correct
False
None
description: The WITH statement when used with open file guarantees that the file object is
closed when the with block exits.
counter = 1
def doLotsOfStuff():
global counter
print counter
1
3
4 - correct
7
none of the above
description: the counter variable being referenced in the function is the global variable
defined outside of the function. Changes to the variable in the function affect the original
variable.
print "\x48\x49!"
\x48\x49!
4849
4849!
48 49!
HI! - correct
description: \x is an escape sequence that means the following 2 digits are a hexadicmal
number encoding a character.
class parent:
def __init__(self, param):
self.v1 = param
class child(parent):
def __init__(self, param):
self.v2 = param
obj = child(11)
print "%d %d" % (obj.v1, obj.v2)
None None
None 11
11 None
11 11
Error is generated by program - correct
description: AttributeError: child instance has no attribute 'v1'. self.v1 was never created as a
variable since the parent __init__ was not explicitly called.
print kvps['password']
user
bill
password
hillary
Nothing. Python syntax error - correct
description: When initializing a dictionary, key and values are seperated by colon and key-
value pairs are separated by commas.
kvps = {"user":"bill", "password":"hillary"}
class Account:
def __init__(self, id):
self.id = id
id = 666
acc = Account(123)
print acc.id
None
123 - correct
666
SyntaxError, this program will not run
description: class instantiation automatically calls the __init__ method and passes the object
as the self parameter. 123 is assigned to data attribute of the object called id. The 666 value is
not retained in the object as it is not assigned to a data attribute of the class/object.
name[5] = 'X'
print name
snow storm
snowXstorm
snow Xtorm
ERROR, this code will not run - correct
description: TypeError. You can not modify the contents of a string
for i in range(2):
print i
for i in range(4,6):
print i
2, 4, 6
0, 1, 2, 4, 5, 6
0, 1, 4, 5 - correct
0, 1, 4, 5, 6, 7, 8, 9
1, 2, 4, 5, 6
description: If only 1 number is supplied to range it is the end of the range. The default
beginning of a range is 0. The range will include the beginning of the range and all numbers
up to but not including the end of the range.
values = [1, 2, 1, 3]
nums = set(values)
def checkit(num):
if num in nums:
return True
else:
return False
values = [2, 3, 2, 4]
def my_transformation(num):
return num ** 2
for i in map(my_transformation, values):
print i
2324
4648
1 1.5 1 2
1112
4 9 4 16 - correct
description: map will call the function for each value in the list. The ** operator in the
function raises the parameter to the power of 2.
import pickle
class account:
def __init__(self, id, balance):
self.id = id
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
myac = account('123', 100)
myac.deposit(800)
myac.withdraw(500)
myac.deposit(200)
print myac.balance
fd = open( "archive", "r" )
myac = pickle.load( fd )
fd.close()
print myac.balance
500 300
500 500
600 400 - correct
600 600
300 500
description: pickle will store the state of the account object to file when its value is 400.
After storing the value to file 200 is added and 600 is printed. After printing 600 the object
form file is reloaded from file and printed with a value of 400.
import math
print math.floor(5.5)
5
5.0 - correct
5.5
6
6.0
description: the floor method will return the largest integer value less than or equal to the
parameter as a float type.
class Person:
def __init__(self, id):
self.id = id
obama = Person(100)
obama.__dict__['age'] = 49
1
2
49
50
51 - correct
description: We have created a member variable named 'age' by adding it directly the objects
dictionary. The value of 'age' is initialized to 49. There are 2 items in the dictionary, 'age' and
'id', therefore the sum of the 'age' value 49 and then size of the dictionary, 2 items, is 51.
x = "foo "
y = 2
print x + y
foo
foo foo
foo 2
2
An exception is thrown - correct
description: Python is a strongly typed language. Once a variable has a type, it must be
casted to change the type. x is a string and y is an integer. Trying to concatenate them will
cause an exception of type TypeError
def simpleFunction():
"This is a cool simple function that returns 1"
return 1
print simpleFunction.__doc__[10:14]
simpleFunction
simple
func
funtion
cool - correct
description: There is a docstring defined for this method, by putting a string on the first line
after the start of the function definition. The docstring can be referenced using the __doc__
attribute of the function.
sys.path.append('/root/mods')
Changes the location that the python executable is run from
Changes the current working directory
Adds a new directory to seach for python modules that are imported - correct
Removes all directories for mods
Changes the location where sub-processes are searched for after they are launched
description: The list sys.path contains, in order, all the directories to be searched when trying
to load a module
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
3
7
13 - correct
14
15
description: search will see if the pattern exists anywhere in the string, while match will only
check if the pattern exists in the beginning of the string.
Question #38:
Which of the following print statements will print all the names in the list
on a seperate line
names = ['Ramesh', 'Rajesh', 'Roger', 'Ivan', 'Nico']
correct
print "\n".join(names) -
print names.join("\n")
print names.concatenate("\n")
print names.append("\n")
print names.join("%s\n", names)
description: Only A is valid syntax. There is a join method to string objects which takes an
iterable object as parameter and combines the string calling the method in between each item
to produce a resulting string.
Question #39: True or false? Code indentation must be 4 spaces when creating a code
block?
if error:
# four spaces of indent are used to create the block
print "%s" % msg
True
False - correct
description: This is false. Indentation needs to be consistent. A specific number of spaces
used for indentation is not prescribed by the language.
Question #40:
Assuming the filename for the code below is /usr/lib/python/person.py
and the program is run as:
python /usr/lib/python/person.py
class Person:
def __init__(self):
pass
def getAge(self):
print __name__
p = Person()
p.getAge()
Person
getAge
usr.lib.python.person
__main__ - correct
An exception is thrown
description: If the module where the reference to __name__ is made has been imported from
another file, then the module name will be in the variable in the form of the filename without
the path or file extension. If the code is being run NOT as the result of an import, the variable
will have the special value "__main__".
foo = {}
print type(foo)
set
dict - correct
list
tuple
object
description: Curly braces are the syntax for a dictionary declaration
foo = (3, 4, 5)
print type(foo)
int
list
tuple - correct
dict
set
description: Parentheses are used to initialize a tuple.
country_counter = {}
def addone(country):
if country in country_counter:
country_counter[country] += 1
else:
country_counter[country] = 1
addone('China')
addone('Japan')
addone('china')
print len(country_counter)
0
1
2
3 - correct
4
description: The len function will return the number of keys in a dictionary. In this case 3
items have been added to the dictionary. Note that the key's to a dictionary are case sensitive.
confusion = {}
confusion[1] = 1
confusion['1'] = 2
confusion[1] += 1
sum = 0
for k in confusion:
sum += confusion[k]
print sum
1
2
3
4 - correct
5
description: Note that keys to a dictionary can be mixed between strings and integers and
they represent different keys.
confusion = {}
confusion[1] = 1
confusion['1'] = 2
confusion[1.0] = 4
sum = 0
for k in confusion:
sum += confusion[k]
print sum
2
4
6 - correct
7
An exception is thrown
description: Note from python docs: "if two numbers compare equal (such as 1 and 1.0) then
they can be used interchangeably to index the same dictionary entry. (Note however, that
since computers store floating-point numbers as approximations it is usually unwise to use
them as dictionary keys.)"
boxes = {}
jars = {}
crates = {}
boxes['cereal'] = 1
boxes['candy'] = 2
jars['honey'] = 4
crates['boxes'] = boxes
crates['jars'] = jars
print len(crates[boxes])
1
2
4
7
An exception is thrown - correct
description: Keys can only be immutable types, so a dictionary can not be used as a key. In
the print statement the dictionary is used as the key instead of the string 'boxes'. Had the string
been used it would have printed the length of the boxes dictionary which is 2.
numberGames = {}
numberGames[(1,2,4)] = 8
numberGames[(4,2,1)] = 10
numberGames[(1,2)] = 12
sum = 0
for k in numberGames:
sum += numberGames[k]
names2[0] = 'Alice'
names3[1] = 'Bob'
sum = 0
for ls in (names1, names2, names3):
if ls[0] == 'Alice':
sum += 1
if ls[1] == 'Bob':
sum += 10
print sum
11
12 - correct
21
22
33
description: When assigning names1 to names2, we create a second reference to the same
list. Changes to names2 affect names1. When assigning the slice of all elements in names1 to
names3, we are creating a full copy of names1 which can be modified independently.
loc = names1.index("Edward")
print loc
-1
0
4
Edward
An exception is thrown - correct
description: If index can not find the specified value in the list an exception is thrown.
if 'amir' in names1:
print 1
else:
print 2
1
2 - correct
An exception is thrown
description: the in keyword can be used to search for a value in a list, set, or dict. In this case
the search fails, because the string value is case sensitive.
i
a
c - correct
C
An exception is thrown
description: List Comprehensions are a shorthand to creating a new list with the all the values
in a original list modified by some python expression.
numbers = [1, 2, 3, 4]
numbers.append([5,6,7,8])
print len(numbers)
4
5 - correct
8
12
An exception is thrown
description: When a list is passed to the append method of list, the entire list is added as an
element of the list. The lists are not merged.
Question #56: Which of the following data structures can be used with the "in" operator
to check if an item is in the data structure?
list
set
dictionary
None of the above
All of the above - correct
description: The "in" operator can be used with all 3 of these data structures.
Question #57: What gets printed?
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
print len(list1 + list2)
2
4
5
8 - correct
An exception is thrown
description: The + operator appends the elements in each list into a new list
def addItem(listParam):
listParam += [1]
mylist = [1, 2, 3, 4]
addItem(mylist)
print len(mylist)
1
4
5 - correct
8
An exception is thrown
description: The list is passed by reference to the function and modifications to the function
parameter also effect the original list.
my_tuple = (1, 2, 3, 4)
my_tuple.append( (5, 6, 7) )
print len(my_tuple)
1
2
5
7
An exception is thrown - correct
description: Tuples are immutable and don't have an append method. An exception is thrown
in this case.
12
2 1 - correct
An exception is thrown
This program has undefined behavior
description: This is valid python code. This is assignment multiple variables at once. The
values in b and a are being assigned to a and b, respectively.
def print_header(str):
print "+++%s+++" % str
print_header.category = 1
print_header.text = "some info"
print_header("%d %s" % \
(print_header.category, print_header.text))
str
int
tuple - correct
list
dict
description: param2 aggregates remaining parameters into a tuple.
Question #63: What gets printed?
dostuff('capitals', Arizona='Phoenix',
California='Sacramento', Texas='Austin')
in
str
tuple
list
dict - correct
description: param2 aggregates the remaining parameters into a dictionary.
myfunc(*nums)
1
3 - correct
6
10
An exception is thrown
description: *nums will unpack the list into individual elements to be passed to the function.
Question #65: How do you create a package so that the following reference will work?
p = mytools.myparser.MyParser()
Declare the myparser package in mytools.py
Create an __init__.py in the home dir
Inside the mytools dir create a __init__.py and myparser.py - correct
Create a myparser.py directory inside the mytools directory
This can not be done
description: In order to create a package create a directory for the package name and then put
an __init__.py file in te directory.
Question #66: What gets printed?
class A:
def __init__(self, a, b, c):
self.x = a + b + c
a = A(1,2,3)
b = getattr(a, 'x')
setattr(a, 'x', b+1)
print a.x
1
2
3
6
7 - correct
description: getattr can be used to get the value of a member variable of an object. setattr can
be used to set it.
class NumFactory:
def __init__(self, n):
self.val = n
def timesTwo(self):
self.val *= 2
def plusTwo(self):
self.val += 2
f = NumFactory(2)
for m in dir(f):
mthd = getattr(f,m)
if callable(mthd):
mthd()
print f.val
2
4
6
8
An exception is thrown - correct
description: An exception will be thrown when trying to call the __init__ method of the
object without any parameters: TypeError: __init__() takes exactly 2 arguments (1 given)
one = chr(104)
two = chr(105)
print "%s%s" % (one, two)
hi - correct
h
None
104105
104
description: chr is a built in function that converts an ascii code to a 1 letter string.
x = 0
y = 1
a = cmp(x,y)
if a < x:
print "a"
elif a == x:
print "b"
else:
print "c"
a - correct
b
c
description: cmp returns a value less than 0 if x is less than y.
cmp returns 0 if x equals y.
cmp returns a value greater than 0 if x is greater than y.
x = 1
y = "2"
z = 3
sum = 0
for i in (x,y,z):
if isinstance(i, int):
sum += i
print sum
2
3
4 - correct
6
An exception is thrown
description: isinstance will return true if the first parameter is an instance of the class type of
the second parameter.
Question #71: What gets printed (with python version 2.X) assuming the user enters
the following at the prompt?
#: foo
a = input("#: ")
print a
f
foo
#: foo
An exception is thrown - correct
description: The input function is equivalent to:
eval(raw_input(prompt)) This function will attempt to execute the text tempted at the prompt
as python code. In the case of this input, invalid python code was entered an exception is
thrown
x = sum(range(5))
print x
4
5
10 - correct
15
An exception is thrown
description: range(5) produces a list of the numbers 0, 1, 2, 3, 4.
sum will add all the numbers in the list.
Question #73: If the user types '0' at the prompt what gets printed?
def getinput():
print "0: start"
print "1: stop"
print "2: reset"
x = raw_input("selection: ")
try:
num = int(x)
if num > 2 or num < 0:
return None
return num
except:
return None
num = getinput()
if not num:
print "invalid"
else:
print "valid"
valid
invalid - correct
An exception is thrown
description: 0 is returned from getinput. Remember that both 0, None, empty sequences and
some other forms all evaluate to False in truth testing.
1
2
7
10 - correct
An exception is thrown
description: Assignment will provide another reference to the same dictionary. Therefore the
change to the original dictionary also is changing the copy.
aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }
theCopy = kvps.copy()
kvps['1'][0] = 5
import copy
aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }
theCopy = copy.deepcopy(kvps)
kvps['1'][0] = 5
1
2
6 - correct
10
An exception is thrown
description: A deep copy will copy all the keys and values inside a dictionary. Therefore the list
inside the dictionary are different in the first and second dictionaries of this example.
x = sum(kvps.values())
print x
15
51 - correct
150
An exception is thrown
description: the update method of dictionary will update the values that have the same keys
as the newData with newData's values.
Question #80:What gets printed (with python version 3.X) assuming the user enters the
following at the prompt?
#: foo
a = input("#: ")
print a
f
foo - correct
Not a number
An exception is thrown
description: The input function in python 3.x is the same as the raw_input function in python
2.x.
Therefore foo will be assigned to 'a' and printed.
1.12 ___________ translates high-level language program into machine language program.
A. An assembler
B. A compiler
C. CPU
D. The operating system
Section 1.4 Operating Systems
1.13 ____________ is an operating system.
A. Java
B. C++
C. Windows XP
D. Visual Basic
E. Python
1.20 To run python script file named t.py, use the command ________.
A. execute python t.py
B. run python t.py
C. python t.py
D. go python t.py
A.
print("Programming is fun")
print("Python is fun")
B.
print("Programming is fun")
print("Python is fun")
C.
print("Programming is fun)
print("Python is fun")
D.
print("Programming is fun)
print("Python is fun")
A. A
B. B
C. C
D. D
I:
print("Programming is fun")
print("Python")
print("Computer Science")
II:
print("Programming is fun")
print("Python")
print("Computer Science")
III:
print("Programming is fun")
print("Python")
print("Computer Science")
IV:
print("Programming is fun")
print("Python")
print("Computer Science")
A. I
B. II
C. III
D. IV
2.3 If you enter 1 2 3 in three separate lines, when you run this program, what will be
displayed?
print("Enter three numbers: ")
number1 = eval(input())
number2 = eval(input())
number3 = eval(input())
# Compute average
average = (number1 + number2 + number3) / 3
# Display result
print(average)
A. 1.0
B. 2.0
C. 3.0
D. 4.0
2.4 _______ is the code in natural language mixed with some program code.
A. Python program
B. A Python statement
C. Pseudocode
D. A flowchart diagram
2.5 If you enter 1 2 3 in one line, when you run this program, what will happen?
2.6 You can place the line continuation symbol __ at the end of a line to tell the interpreter
that the statement is continued on the next line.
A. /
B. \
C. #
D. *
E. &
2.8 An identifier can contain digits, but cannot start with a digit?
A. true
B. false
2.9 Which of the following is a valid identifier?
A. $343
B. mile
C. 9X
D. 8+9
E. max_radius
# Compute average
average = (number1 + number2 + number3) / 3
# Display result
print(average)
A. 1.0
B. 2.0
C. 3.0
D. 4.0
x=1
x=2*x+1
print(x)
A. 0
B. 1
C. 2
D. 3
E. 4
2.13 What will be displayed by the following code?
x=1
x = x + 2.5
print(x)
A. 1
B. 2
C. 3
D. 3.5
E. The statements are illegal
2.15 To following code reads two number. Which of the following is the correct input for the
code?
x, y = eval(input("Enter two numbers: "))
A. 1 2
B. "1 2"
C. 1, 2
D. 1, 2,
2.17 In the expression 45 / 4, the values on the left and right of the / symbol are called ____.
A. operators
B. operands
C. parameters
D. arguments
25 % 1 is _____
2.21
A. 1
B. 2
C. 3
D. 4
E. 0
24 % 5 is _____
2.22A. 1
B. 2
C. 3
D. 4
E. 0
2 ** 3 evaluates to __________.
2.23
A. 9
B. 8
C. 9.0
D. 8.0
x=1
y=x=x+1
print("y is", y)
A. y is 0.
B. y is 1 because x is assigned to y first.
C. y is 2 because x + 1 is assigned to x and then x is assigned to y.
D. The program has a compile error since x is redeclared in the statement int y = x = x +
1.
2.27 Which of the following is equivalent to 0.025?
A. 0.25E-1
B. 2.5e-2
C. 0.0025E1
D. 0.00025E2
E. 0.0025E+1
x=1
x *= x + 1
A. x is 1
B. x is 2
C. x is 3
D. x is 4
x=2
y=1
x *= y + 1
A. x is 1.
B. x is 2.
C. x is 3.
D. x is 4.
2.33 To add a value 1 to variable x, you write
A. 1 + x = x
B. x += 1
C. x := 1
D. x = x + 1
E. x = 1 + x
(A) x -= x + 4
(B) x = x + 4 - x
(C) x = x - (x + 4)
A. (A) and (B) are the same
B. (A) and (C) are the same
C. (B) and (C) are the same
D. (A), (B), and (C) are the same
x=1
y=2
x *= y + 1
A. x is 1
B. x is 2
C. x is 3
D. x is 4
What is round(6.5)?
3.4
A. 4
B. 5
C. 6
D. 7
E. 8
What is round(7.5)?
3.5
A. 4
B. 5
C. 6
D. 7
E. 8
B. No
3.13 Suppose x is a char variable with a value 'b'. What will be displayed by the statement
print(chr(ord(x) + 1))?
A. a
B. b
C. c
D. d
3.15 Suppose i is an int type variable. Which of the following statements display the
character whose Unicode is stored in variable i?
A. print(i)
B. print(str(i))
C. print(int(i))
D. print(chr(i))
3.16 The Unicode of 'a' is 97. What is the Unicode for 'c'?
A. 96
B. 97
C. 98
D. 99
3.28 To format a number x to 3 digits after the decimal point, use _______.
A. format(x, "5.3f")
B. format("5.3f", x)
C. format(x, "5.4f")
D. format("5.3f", x)
3.29 Suppose x is 345.3546, what is format(x, "10.3f")? (note b represents a blank space)
A. bb345.355
B. bbb345.355
C. bbbb345.355
D. bbb345.354
E. bbbb345.354
3.30 What will be displayed by the following code? ? (note ? represents a blank space)
3.31 What will be displayed by the following code? ? (note ? represents a blank space)
3.32 Suppse number contains integer value 4, which of the following statement is correct?
A. print(format(number, "2d"), format(number ** 1.5, "4d"))
B. print(format(number, "2d"), format(number ** 1.5, "4.2d"))
C. print(format(number, "2d"), format(number ** 1.5, "4.2f"))
D. print(format(number, "2f"), format(number ** 1.5, "4.2f"))
E. print(format(number, "2.1f"), format(number ** 1.5, "4.2f"))
3.36 To draw a circle of diameter 10 with filled color red, use _________.
A. turtle.circle(5, "red")
B. turtle.circle(10, "red")
C. turtle.dot(5, "red")
D. turtle.dot(10, "red")
Chapter 4 Selections
A. <
B. <=
C. =<
D. <<
E. !=
Sections 4.4-4.10
4.7 Which of the following code displays the area of a circle if the radius is positive.
A. if radius != 0: print(radius * radius * 3.14159)
B. if radius >= 0: print(radius * radius * 3.14159)
C. if radius > 0: print(radius * radius * 3.14159)
D. if radius <= 0: print(radius * radius * 3.14159)
x=0
if x < 4:
x=x+1
print("x is", x)
A. x is 0
B. x is 1
C. x is 2
D. x is 3
E. x is 4
4.9 Suppose isPrime is a boolean variable, which of the following is the correct and best
statement for testing if isPrime is true.
A. if isPrime = True:
B. if isPrime == True:
C. if isPrime:
D. if not isPrime = False:
E. if not isPrime == False:
even = False
if even = True:
print("It is even!")
A. The program has a syntax error in line 1 (even = False)
B. The program has a syntax error in line 2 if even = True is not a correct condition. It
should be replaced by if even == True: or if even:.
C. The program runs, but displays nothing.
D. The program runs and displays It is even!.
even = False
if even:
print("It is even!")
A. The code displays It is even!
B. The code displays nothing.
C. The code is wrong. You should replace if even: with if even == True:
D. The code is wrong. You should replace if even: with if even = True:
4.12 Suppose x = 1, y = -1, and z = 1. What will be displayed by the following statement?
if x > 0:
if y > 0:
print("x > 0 and y > 0")
elif z > 0:
print("x < 0 and z > 0")
A. x > 0 and y > 0
B. x < 0 and z > 0
C. x < 0 and z < 0
D. nothing displayed
temperature = 50
Code 1:
if number % 2 == 0:
even = True
else:
even = False
Code 2:
even = number % 2 == 0
A. Code 1 has compile errors.
B. Code 2 has compile errors.
C. Both Code 1 and Code 2 have compile errors.
D. Both Code 1 and Code 2 are correct, but Code 2 is better.
4.15 Suppose income is 4001, what will be displayed by f the following code?
4.16 Suppose you write the code to display "Cannot get a driver's license" if age is less than
16
and "Can get a driver's license" if age is greater than or equal to 16.
Which of the following code is correct?
I:
if age < 16:
print("Cannot get a driver's license")
if age >= 16:
print("Can get a driver's license")
II:
if age < 16:
print("Cannot get a driver's license")
else:
print("Can get a driver's license")
III:
if age < 16:
print("Cannot get a driver's license")
elif age >= 16:
print("Can get a driver's license")
IV:
if age < 16:
print("Cannot get a driver's license")
elif age == 16:
print("Can get a driver's license")
elif age > 16:
print("Can get a driver's license")
A. I and II
B. II and III
C. I, II, and III
D. III and IV
E. All correct
4.17 Suppose you write the code to display "Cannot get a driver's license" if age is less than
16
and "Can get a driver's license" if age is greater than or equal to 16.
Which of the following code is the best?
I:
if age < 16:
print("Cannot get a driver's license")
if age >= 16:
print("Can get a driver?s license")
II:
if age < 16:
print("Cannot get a driver's license")
else:
print("Can get a driver's license")
III:
if age < 16:
print("Cannot get a driver's license")
elif age >= 16:
print("Can get a driver's license")
IV:
if age < 16:
print("Cannot get a driver's license")
elif age == 16:
print("Can get a driver's license")
elif age > 16:
print("Can get a driver's license")
A. I
B. II
C. III
D. IV
4.20 Which of the following is the correct expression that evaluates to True if the number x
is between 1 and 100 or the number is negative?
21. To check whether a char variable ch is an uppercase letter, you write ___________.
A. (ch >= 'A' and ch >= 'Z')
B. (ch >= 'A' and ch <= 'Z')
C. (ch >= 'A' or ch <= 'Z')
D. ('A' <= ch <= 'Z')
ch = 'F'
if ch >= 'A' and ch <= 'Z':
print(ch)
A. F
B. f
C. nothing
D. F f
4.29 Analyze the following code fragments that assign a boolean value to the variable even.
Code 1:
if number % 2 == 0:
even = True
else:
even = False
Code 2:
even = True if number % 2 == 0 else False
Code 3:
even = number % 2 == 0
A. Code 2 has a syntax error, because you cannot have True and False literals in the
conditional expression.
B. Code 3 has a syntax error, because you attempt to assign number to even.
C. All three are correct, but Code 1 is preferred.
D. All three are correct, but Code 2 is preferred.
E. All three are correct, but Code 3 is preferred.
4.30 What will be displayed by the following code?
isCorrect = False
print("Correct" if isCorrect else "Incorrect")
A. Correct
B. Incorrect
C. nothing
D. Correct Incorrect
Chapter 5 Loops
x=0
while x < 4:
x=x+1
print("x is", x)
A. x is 0
B. x is 1
C. x is 2
D. x is 3
E. x is 4
count = 0
while count < 100:
# Point A
print("Welcome to Python!")
count += 1
# Point B
# Point C
A. count < 100 is always True at Point A
B. count < 100 is always True at Point B
C. count < 100 is always False at Point B
D. count < 100 is always True at Point C
E. count < 100 is always False at Point C
5.4 How many times will the following code print "Welcome to Python"?
count = 0
while count < 10:
print("Welcome to Python")
A. 8
B. 9
C. 10
D. 11
E. infinite number of times
5.5 What will be displayed when the following code is executed?
number = 6
while number > 0:
number -= 3
print(number, end = ' ')
A. 6 3 0
B. 6 3
C. 3 0
D. 3 0 -3
E. 0 -3
A:
for count in range(1, 10):
print("Welcome to Python")
B:
for count in range(0, 10):
print("Welcome to Python")
C:
for count in range(1, 11):
print("Welcome to Python")
D:
for count in range(1, 12):
print("Welcome to Python")
A. BD
B. ABC
C. AC
D. BC
E. AB
5.11 Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100?
A:
sum = 0
for i in range(1, 99):
sum += i / (i + 1)
print("Sum is", sum)
B:
sum = 0
for i in range(1, 100):
sum += i / (i + 1)
print("Sum is", sum)
C:
sum = 0
for i in range(1.0, 99.0):
sum += i / (i + 1)
print("Sum is", sum)
D:
sum = 0
for i in range(1.0, 100.0):
sum += i / (i + 1)
print("Sum is", sum)
A. BCD
B. ABCD
C. B
D. CDE
E. CD
y=0
for i in range(0, 10):
y += i
print(y)
A. 10
B. 11
C. 12
D. 13
E. 45
y=0
for i in range(0, 10, 2):
y += i
print(y)
A. 9
B. 10
C. 11
D. 20
y=0
for i in range(10, 1, -2):
y += i
print(y)
A. 10
B. 40
C. 30
D. 20
5.18 To add 0.01 + 0.02 + ... + 1.00, what order should you use to add the numbers to get
better accuracy?
A. add 0.01, 0.02, ..., 1.00 in this order to a sum variable whose initial value is 0.
B. add 1.00, 0.99, 0.98, ..., 0.02, 0.01 in this order to a sum variable whose initial value is
0.
Section 5.6 Case Studies
5.19 How many times is the print statement executed?
for i in range(10):
for j in range(10):
print(i * j)
A. 100
B. 20
C. 10
D. 45
for i in range(10):
for j in range(i):
print(i * j)
A. 100
B. 20
C. 10
D. 45
while True:
@datascience-trainer
if balance < 9: break
balance = balance - 9
A. Yes
B. No
5.22 What is sum after the following loop terminates?
sum = 0
item = 0
while item < 5:
item += 1
sum += item
if sum > 4: break
print(sum)
A. 5
B. 6
C. 7
D. 8
sum = 0
item = 0
while item < 5:
item += 1
sum += item
if sum >= 4: continue
print(sum)
A. 15
B. 16
C. 17
D. 18
balance = 10
while True:
if balance < 9: continue
balance = balance - 9
A. Yes
B. No
Section 5.8 Case Study: Displaying Prime Numbers
5.25 What will be displayed by after the following loop terminates?
number = 25
isPrime = True
i=2
while i < number and isPrime:
if number % i == 0:
isPrime = False
i += 1
number = 25
isPrime = True
for i in range(2, number):
if number % i == 0:
isPrime = False
break
print("i is", i, "isPrime is", isPrime)
A. i is 5 isPrime is True
B. i is 5 isPrime is False
C. i is 6 isPrime is True
D. i is 6 isPrime is False
5.29 Suppose the input for number is 9. What will be displayed by the following program?
isPrime = True
for i in range(2, number):
if number % i == 0:
isPrime = False
print("i is", i)
if isPrime:
print(number, "is prime")
break
else:
print(number, "is not prime")
A. i is 3 followed by 9 is prime
B. i is 3 followed by 9 is not prime
C. i is 2 followed by 9 is prime
D. i is 2 followed by 9 is not prime
Chapter 6 Functions
@datascience-trainer
B. function name and parameter list
C. parameter list
6.5 Does the function call in the following function cause syntax errors?
import math
def main():
math.sin(math.pi)
main()
A. Yes
B. No
6.6 Each time a function is invoked, the system stores parameters and local variables in an
area of memory, known as _______, which stores elements in last-in first-out fashion.
A. a heap
B. storage area
C. a stack
D. an array
def f(number):
# Missing function body
print(f(5))
A. aaaaa
B. aaaa
C. aaa
D. invalid call
E. infinite loop
k=2
nPrint("A message", k)
A. 0
B. 1
C. 2
D. 3
x=1
def f1():
y=x+2
print(y)
f1()
print(x)
A. 1 3
B. 3 1
C. The program has a runtime error because x is not defined.
D. 1 1
E. 3 3
x=1
def f1():
x=3
print(x)
f1()
print(x)
A. 1 3
B. 3 1
C. The program has a runtime error because x is not defined.
D. 1 1
E. 3 3
x=1
def f1():
x=x+2
print(x)
f1()
print(x)
A. 1 3
B. 3 1
C. The program has a runtime error because x is not defined.
D. 1 1
E. 3 3
x=1
def f1():
global x
x=x+2
print(x)
f1()
print(x)
A. 1 3
B. 3 1
C. The program has a runtime error because x is not defined.
D. 1 1
E. 3 3
7.6 The ________ creates an object in the memory and invokes __________.
A. the __init__ method
B. the init method
C. the initialize method
D. the __str__ method
class A:
def __init__(self, s):
self.s = s
def print(self):
print(s)
a = A("Welcome")
a.print()
A. The program has an error because class A does not have a constructor.
B. The program has an error because class A should have a print method with signature
print(self, s).
C. The program has an error because class A should have a print method with signature
print(s).
D. The program would run if you change print(s) to print(self.s).
class A:
def __init__(self, s):
self.s = s
def print(self):
print(self.s)
a = A()
a.print()
A. The program has an error because class A does not have a constructor.
B. The program has an error because s is not defined in print(s).
C. The program runs fine and prints nothing.
D. The program has an error because the constructor is invoked without an argument.
def print(self):
print(self.s)
a = A()
a.print()
A. The program has an error because class A does not have a constructor.
B. The program has an error because s is not defined in print(s).
C. The program runs fine and prints nothing.
D. The program has an error because the constructor is invoked without an argument.
E. The program runs fine and prints Welcome.
7.10 Given the declaration x = Circle(), which of the following statement is most accurate.
A. x contains an int value.
B. x contains an object of the Circle type.
C. x contains a reference to a Circle object.
D. You can assign an int value to x.
def getY(self):
return self.__y
a = A()
print(a.x)
A. The program has an error because x is private and cannot be access outside of the
class.
B. The program has an error because y is private and cannot be access outside of the
class.
C. The program has an error because you cannot name a variable using __y.
D. The program runs fine and prints 1.
E. The program runs fine and prints 0.
7.12 Analyze the following code:
class A:
def __init__(self):
self.x = 1
self.__y = 1
def getY(self):
return self.__y
a = A()
print(a.__y)
A. The program has an error because x is private and cannot be access outside of the
class.
B. The program has an error because y is private and cannot be access outside of the
class.
C. The program has an error because you cannot name a variable using __y.
D. The program runs fine and prints 1.
E. The program runs fine and prints 0.
class A:
def __init__(self):
self.x = 1
self.__y = 1
def getY(self):
return self.__y
a = A()
a.x = 45
print(a.x)
A. The program has an error because x is private and cannot be access outside of the
class.
B. The program has an error because y is private and cannot be access outside of the
class.
C. The program has an error because you cannot name a variable using __y.
D. The program runs fine and prints 1.
E. The program runs fine and prints 45.
def A:
def __init__(self):
__a = 1
self.__b = 1
self.__c__ = 1
__d__ = 1
# Other methods omitted
class A:
def __init__(self):
self.x = 1
self.__y = 1
def getY(self):
return self.__y
a = A()
a.__y = 45
print(a.getX())
A. The program has an error because x is private and cannot be access outside of the
class.
B. The program has an error because y is private and cannot be access outside of the
class.
C. The program has an error because you cannot name a variable using __y.
D. The program runs fine and prints 1.
E. The program runs fine and prints 45.
def main():
myCount = Count()
times = 0
for i in range(0, 100):
increment(myCount, times)
print("myCount.count =", myCount.count, "times =", times)
class Count:
def __init__(self):
self.count = 0
main()
A. count is 101 times is 0
B. count is 100 times is 0
C. count is 100 times is 100
D. count is 101 times is 101
B. rogramming is fun
C. Programming is f
D. Programming is fu
E. Programming is
class Count:
def __init__(self, count = 0):
self.__count = count
c1 = Count(2)
c2 = Count(2)
print(id(c1) == id(c2), end = " ")
s1 = "Good"
s2 = "Good"
print(id(s1) == id(s2))
A. True False
B. True True
C. False True
D. False False
class Name:
def __init__(self, firstName, mi, lastName):
self.firstName = firstName
self.mi = mi
self.lastName = lastName
firstName = "John"
name = Name(firstName, 'F', "Smith")
firstName = "Peter"
name.lastName = "Pan"
print(name.firstName, name.lastName)
@datascience-trainer
A. The program displays Peter Pan.
B. The program displays John Pan.
C. The program displays Peter Smith.
D. The program displays John Smith.
class MyDate:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
class Name:
def __init__(self, firstName, mi, lastName, birthDate):
self.firstName = firstName
self.mi = mi
self.lastName = lastName
self.birthDate = birthDate
birthDate = MyDate(1990, 1, 1)
name = Name("John", 'F', "Smith", birthDate)
birthDate = MyDate(1991, 1, 1)
birthDate.year = 1992
print(name.birthDate.year)
A. The program displays 1990.
B. The program displays 1991.
C. The program displays 1992.
D. The program displays no thing.
8.27 If a class defines the __str__(self) method, for an object obj for the class, you can use
______ to invoke the __str__ method.
A. obj.__str__()
B. str(obj)
C. obj.str()
D. __str__(obj)
Sections 9.2-9.4
9.1 How do you create a window?
A. window = newWindow()
B. window = Window()
C. window = Frame()
D. window = Tk()
9.2 How do you create a frame?
A. frame = newWindow()
B. frame = Window()
C. frame = Frame()
D. frame = Tk()
9.5 To create a button under parent window with command processButton, use _______.
A. Button(text = "OK", fg = "red", command = processButton)
B. Button(window, text = "OK", fg = "red")
C. Button(window, text = "OK", fg = "red")
D. Button(window, text = "OK", command = processButton)
9.7 Assume v1 = IntVar(), how do you create a check button under parent frame1 with
variable bound to v1?
A. Checkbutton(frame1, text = "Bold", command = processCheckbutton)
B. Checkbutton(frame1, text = "Bold", variable = v1.get())
C. Checkbutton(frame1, text = "Bold", variable = v1, command = processCheckbutton)
D. Checkbutton(frame1, text = "Bold", variable = v1.set(), command =
processCheckbutton)
9.8 Assume v1 = IntVar(), how do you create a radio button under parent frame1 with
variable bound to v1 and value 1?
A. Checkbutton(frame1, text = "Bold", command = processCheckbutton)
B. Checkbutton(frame1, text = "Bold", variable = v1.get())
C. Checkbutton(frame1, text = "Bold", variable = v1, command = processCheckbutton)
D. Radiobutton(frame1, text = "Yellow", bg = "yellow", variable = v1, value = 1,
command = processRadiobutton)
9.9 Assume name = StringVar(), how do you create a text field (entry) under parent frame2
with variable bound to name?
A. entryName = Entry(frame2, textvariable = name)
B. entryName = Entry(frame2, variable = name, value = "")
C. entryName = Entry(frame2, textvariable = name, command = processEntry)
D. entryName = Entry(frame2, text = name, command = processEntry)
9.10 How do you create a GUI component for displaying multiple-lines of text?
A. use Label
B. Use Button
C. Use Text
D. Use Message
Section 9.5
9.12 How do you create a canvas under parent frame1 with background color white and
foregroung color green?
A. Canvas(frame1, bg = "white", fg = "green")
B. Canvas(frame1, bg = "white", fg = "green", command = processEvent)
C. Canvas(frame1, bg = "white", command = processEvent)
D. Canvas(frame1, fg = "green", command = processEvent)
Section 9.5
9.13 How do you draw a rectangle centered at 100, 100 with width 100 and height 100 on
canvas?
A. canvas.create_rect(100, 100, 100, 100)
B. canvas.create_rectangle(100, 100, 100, 100)
C. canvas.create_rect(100 - 50, 100 - 50, 100 + 50, 100 + 50)
D. canvas.create_rectangle(100 - 50, 100 - 50, 100 + 50, 100 + 50)
9.14 How do you draw a circle rectangle centered at 100, 100 with radius 100 on canvas?
A. canvas.create_oval(100, 100, 100, 100)
B. canvas.create_oval(100 - 100, 100 - 100, 100 + 100, 100 + 100)
C. canvas.create_oval(100 - 50, 100 - 50, 100 + 50, 100 + 50)
D. canvas.create_circle(100 - 100, 100 - 100, 100 + 100, 100 + 100)
9.15 How do you draw an arc centered at 100, 100 with radius 20, starting angle 15, ending
angle 50, filled with red color on canvas?
A. canvas.create_arc(100 - 20, 100 - 20, 100 + 20, 100 + 20, fill = "red", start = 15,
extent = 50)
B. canvas.create_arc(100 - 20, 100 - 20, 100 + 20, 100 + 20, fill = "red", start = 15, extent
= 35)
C. canvas.create_arc(100 - 20, 100 - 20, 100 + 20, 100 + 20, filled = "red", start = 15,
extent = 50)
D. canvas.create_arc(100 - 20, 100 - 20, 100 + 20, 100 + 20, fill = "red", start = 15, end =
50)
9.16 How do you draw a red line from 100, 100 to 400, 500?
A. canvas.create_line(100, 100, 100, 500, fill = "red")
B. canvas.create_line(100, 100, 400, 100, fill = "Red")
C. canvas.create_line(100, 100, 400, 500, filled = "red")
D. canvas.create_line(100, 100, 400, 500, fill = "red")
9.17 How do you draw a polygon consisting of points (30, 40), (50, 50), (10, 100) filled with
red color?
A. canvas.create_poly(30, 40, 50, 50, 10, 100, fill = "red")
B. canvas.create_polygon(30, 40, 50, 50, 10, 100, filled = "red")
C. canvas.create_polygon(30, 40, 50, 50, 10, 100, fill = "red")
D. canvas.create_polygon((30, 40), (50, 50), (10, 100), fill = "red")
9.18 How do you display a text "Good morning" centered at 30, 40 with color red?
A. canvas.create_text(30, 40, text = "Good morning", fill = "red")
B. canvas.create_polygon(30, 40, 50, 50, 10, 100, filled = "red")
C. canvas.create_polygon(30, 40, 50, 50, 10, 100, fill = "red")
D. canvas.create_polygon((30, 40), (50, 50), (10, 100), fill = "red")
9.20 To place a button in a specified row and column in its parent container, use ________.
A. pack manager
B. grid manager
C. place manager
D. flow manager
9.21 Which option do you use to put the components in a container using the pack manager
in the same row?
A. component.pack(LEFT)
B. component.pack(side = LEFT)
C. component.pack(side = "LEFT")
D. component.pack("LEFT")
9.23 Using a grid manager, you can use the option _________ to place a component in
multiple rows and columns.
A. row
B. column
C. rowspan
D. columnspan
Sections 9.10-9.11
9.30 To display a popup menu, use __________
A. menu.display()
B. menu.post()
C. menu.display(300, 300)
D. menu.post(300, 300)
9.31 To bind a canvas with a left mouse click event p, use __________
A. canvas.left(p)
B. canvas.bind("<Button-1>", p)
C. canvas.bind("Button-1", p)
D. canvas.bind(<Button-1>, p)
9.32 To bind a canvas with a right mouse click event p, use __________
A. canvas.left(p)
B. canvas.bind("<Button-1>", p)
C. canvas.bind("Button-1", p)
D. canvas.bind(<Button-1>, p)
E. canvas.bind("<Button-3>", p)
9.34 The event _____________ is fired when the mouse is moved while the middle mouse is
being held down.
A. <B1-Motion>
B. <B2-Motion>
C. <B3-Motion>
D. <Button-1>
E. <Button-2>
9.35 The event _____________ is fired when the right mouse button is released.
A. <ButtonReleased-1>
B. <ButtonReleased-2>
C. <ButtonReleased-3>
D. <ButtonPressed-1>
E. <ButtonPressed-2>
9.36 The event _____________ is fired when the right mouse button is double-clicked.
A. <Double-Button-1>
B. <Double-Button-2>
C. <Double-Button-3>
D. <Triple-Button-1>
E. <Triple-Button-2>
9.40 To display a warning dialog named "Variable is assigned, but not used", use
__________
A. tkinter.messagebox.showinfo("showinfo", "Variable is assigned, but not used")
B. tkinter.messagebox.showwarning("showwarning", "Variable is assigned, but not
used")
C. tkinter.messagebox.showerror("showerror", "PVariable is assigned, but not used")
D. tkinter.messagebox.askyesno("ashyesno", "Variable is assigned, but not used")
9.41 To display an error dialog named "Variable is not assigned", use __________
A. tkinter.messagebox.showinfo("showinfo", "Variable is not assigned")
B. tkinter.messagebox.showwarning("showwarning", "Variable is not assigned")
C. tkinter.messagebox.showerror("showerror", "Variable is not assigned")
D. tkinter.messagebox.askyesno("ashyesno", "Variable is not assigned")
9.42To display an input dialog named "Is this an integer?", use __________ A.
tkinter.messagebox.showinfo("showinfo", "Is this an integer?")
B. tkinter.messagebox.showwarning("showwarning", "Is this an integer?")
C. tkinter.messagebox.showerror("showerror", "Is this an integer?")
D. tkinter.messagebox.askyesno("ashyesno", "Is this an integer?")
Chapter 10 Lists
10.13 list1 = [11, 2, 23] and list2 = [11, 2, 2], list1 < list2 is ________
A. True
B. False
10.14 list1 = [11, 2, 23] and list2 = [2, 11, 23], list1 == list2 is ________
A. True
B. False
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.sort()?
10.20
A. [3, 4, 5, 20, 5, 25, 1, 3]
B. [1, 3, 3, 4, 5, 5, 20, 25]
C. [25, 20, 5, 5, 4, 3, 3, 1]
D. [1, 3, 4, 5, 20, 5, 25, 3]
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.reverse()?
10.21
A. [3, 4, 5, 20, 5, 25, 1, 3]
B. [1, 3, 3, 4, 5, 5, 20, 25]
C. [25, 20, 5, 5, 4, 3, 3, 1]
D. [1, 3, 4, 5, 20, 5, 25, 3]
E. [3, 1, 25, 5, 20, 5, 4, 3]
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.extend([34, 5])?
10.22
A. [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
B. [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
C. [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
D. [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]
E. [3, 1, 25, 5, 20, 5, 4, 3, 34, 5]
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.pop(1)?
10.23
A. [3, 4, 5, 20, 5, 25, 1, 3]
B. [1, 3, 3, 4, 5, 5, 20, 25]
C. [3, 5, 20, 5, 25, 1, 3]
D. [1, 3, 4, 5, 20, 5, 25]
E. [3, 1, 25, 5, 20, 5, 4]
10.24 Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.pop()?
A. [3, 4, 5, 20, 5, 25, 1]
B. [1, 3, 3, 4, 5, 5, 20, 25]
C. [3, 5, 20, 5, 25, 1, 3]
D. [1, 3, 4, 5, 20, 5, 25]
E. [3, 1, 25, 5, 20, 5, 4]
myList = [1, 5, 5, 5, 5, 1]
max = myList[0]
indexOfMax = 0
for i in range(1, len(myList)):
if myList[i] > max:
max = myList[i]
indexOfMax = i
print(indexOfMax)
A. 0
B. 1
C. 2
D. 3
E. 4
10.28 What will be displayed by the following code?
myList = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
myList[i - 1] = myList[i]
Sections 10.7-10.8
10.30 What will be displayed by the following code?
def f(values):
values[0] = 44
v = [1, 2, 3]
f(v)
print(v)
A. [1, 44]
B. [1, 2, 3, 44]
C. [44, 2, 3]
D. [1, 2, 3]
t=3
v = [1, 2, 3]
f(t, v)
print(t, v[0])
A. 1 1
B. 1 44
C. 3 1
D. 3 44
f(1)
f(2)
v = f(3)
print(v)
A. [1] [2] [3]
B. [1] [1, 2] [1, 2, 3]
C. [1, 2, 3]
D. 1 2 3
10.34 If a key is not in the list, the binarySearch function returns _________.
A. insertion point
B. insertion point - 1
C. -(insertion point + 1)
D. -insertion point
10.35 If the binary search function returns -4, where should the key be inserted if you wish to
insert the key into the list?
A. at index 3
B. at index 4
C. at index 5
D. at index 6
Section 10.11 Sorting Lists
10.36 Use the selectionSort function presented in this section to answer this question.
Assume lst is [3.1, 3.1, 2.5, 6.4, 2.1], what is the content of list after the first iteration of the
outer loop in the function?
A. 3.1, 3.1, 2.5, 6.4, 2.1
B. 2.5, 3.1, 3.1, 6.4, 2.1
C. 2.1, 2.5, 3.1, 3.1, 6.4
D. 3.1, 3.1, 2.5, 2.1, 6.4
E. 2.1, 3.1, 2.5, 6.4, 3.1
10.37 Use the selectionSort function presented in this section to answer this question. What
is list1 after executing the following statements?
list1 = [3.1, 3.1, 2.5, 6.4]
selectionSort(list1)
A. list1 is 3.1, 3.1, 2.5, 6.4
B. list1 is 2.5 3.1, 3.1, 6.4
C. list1 is 6.4, 3.1, 3.1, 2.5
D. list1 is 3.1, 2.5, 3.1, 6.4
11.2 Assume m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], what are len(m)?
A. 0
B. 1
C. 2
D. 3
E. 4
11.3 Assume m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], what are len(m[0])?
A. 0
B. 1
C. 2
D. 3
E. 4
How many elements are in m = [[x, y] for x in range(0, 4) for y in range(0, 4)]?
11.6
A. 8
B. 12
C. 16
D. 32
Assume x = ((1, 2), (3, 4, 5), (5, 6, 5, 9)), what are len(x) are len(x[0])?
11.7
A. 2 and 1
B. 2 and 2
C. 3 and 2
D. 2 and 3
E. 3 and 3
11.8 Assume x = [[1, 2], [3, 4, 5], [5, 6, 5, 9]], what are len(x[0]), len(x[1]), and len(x[2])?
A. 2, 3, and 3
B. 2, 3, and 4
C. 3, 3, and 3
D. 3, 3, and 4
E. 2, 2, and 2
v = values[0][0]
for row in range(0, len(values)):
for column in range(0, len(values[row])):
if v < values[row][column]:
v = values[row][column]
print(v)
A. 1
B. 3
C. 5
D. 6
E. 33
v = values[0][0]
for lst in values:
for element in lst:
if v > element:
v = element
print(v)
A. 1
B. 3
C. 5
D. 6
E. 33
11.11 What will be displayed by the following program?
@datascience-trainer
E. 3 6 10 14
def m(list):
v = list[0]
for e in list:
if v < e: v = e
return v
print(data[1][0][0])
A. 1
B. 2
C. 4
D. 5
E. 6
11.16 What will be displayed the following code?
def ttt(m):
v = m[0][0]
for row in m:
for element in row:
if v < element: v = element
return v
print(ttt(data[0]))
A. 1
B. 2
C. 4
D. 5
E. 6
class B(A):
def __init__(self, j = 0):
self.j = j
def main():
b = B()
print(b.i)
print(b.j)
main()
A. Class B inherits A, but the data field in i in A is not inherited.
B. Class B inherits A and automatically inherits all data fields in A.
C. When you create an object B, you have to pass an integer such as B(5).
D. The data field j cannot be accessed by object b.
class A:
def __init__(self, i = 1):
self.i = i
class B(A):
def __init__(self, j = 2):
super().__init__()
self.j = j
def main():
b = B()
print(b.i, b.j)
main()
A. 0 0
B. 0 1
C. 1 2
D. 0 2
E. 2 1
class ParentClass:
def __init__(self):
self.__x = 1
self.y = 10
def print(self):
print(self.__x, self.y)
class ChildClass(ParentClass):
def __init__(self):
super().__init__()
self.__x = 2
self.y = 20
c = ChildClass()
c.print()
A. 1 10
B. 1 20
C. 2 10
D. 2 20
12.4 Suppose A is a subclass of B, to invoke the __init__ method in B from A, you write
_________.
A. super().__init__()
B. super().__init__(self)
C. B.__init__()
D. B.__init__(self)
12.5 What code can you put in the third line in class B to invoke B's superclass's constructor?
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)
def m1(self):
self.i += 1
class B(A):
def __init__(self, j = 0):
A.__init__(self, 3)
self.j = j
def m1(self):
self.j += 1
def main():
b = B()
b.m1()
print(b.i, b.j)
main()
A. 2 0
B. 3 1
C. 4 0
D. 3 0
E. 4 1
class B(A):
def __new__(self):
print("B's __new__() invoked")
def __init__(self):
print("B's __init__() invoked")
def main():
b = B()
a = A()
main()
A. B's __new__() invoked and followed by A's __init__() invoked
B. B's __new__() invoked followed by A's __new__() invoked
C. B's __new__() invoked, followed by A's __init__() invoked, and followed by A's
__new__() invoked
D. A's __init__() invoked and followed by A's __new__() invoked
def m(self):
self.i = 10
class B(A):
def m(self):
self.i += 1
return self.i
def main():
b = B()
print(b.m())
main()
A. 1
B. 2
C. 10
D. i is not accessible from b.
class A:
def __str__(self):
return "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(a, b, c)
main()
A. C C C
B. A B C
C. A A A
D. B B B
class A:
def __str__(self):
return "A"
class B(A):
def __init__(self):
super().__init__()
class C(B):
def __init__(self):
super().__init__()
def main():
b = B()
a = A()
c = C()
print(a, b, c)
main()
A. C C C
B. A B C
C. A A A
D. B B B
12.13 What will be displayed by the following code?
class A:
def __init__(self, i = 2, j = 3):
self.i = i
self.j = j
def __str__(self):
return "A"
def __eq__(self, other):
return self.i * self.j == other.i * other.j
def main():
x = A(1, 2)
y = A(2, 1)
print(x == y)
main()
A. True
B. False
C. 2
D. 1
class Person:
def getInfo(self):
return "Person's getInfo is called"
def printPerson(self):
print(self.getInfo(), end = ' ')
class Student(Person):
def getInfo(self):
return "Student's getInfo is called"
def main():
Person().printPerson()
Student().printPerson()
main()
A. Person's getInfo is called Person's getInfo is called
B. Person's getInfo is called Student's getInfo is called
C. Student's getInfo is called Person's getInfo is called
D. Student's getInfo is called Student's getInfo is called
12.15 What will be displayed by the following code?
class Person:
def __getInfo(self):
return "Person's getInfo is called"
def printPerson(self):
print(self.__getInfo(), end = ' ')
class Student(Person):
def __getInfo(self):
return "Student's getInfo is called"
def main():
Person().printPerson()
Student().printPerson()
main()
A. Person's getInfo is called Person's getInfo is called
B. Person's getInfo is called Student's getInfo is called
C. Student's getInfo is called Person's getInfo is called
D. Student's getInfo is called Student's getInfo is called
class A:
def __init__(self):
self.setI(20)
print("i from A is", self.i)
def setI(self, i):
self.i = 2 * i;
class B(A):
def __init__(self):
super().__init__()
b = B()
A. The __init__ method of class A is not called.
B. The __init__ method of class A is called and it displays "i from A is 0".
C. The __init__ method of class A is called and it displays "i from A is 40".
D. The __init__ method of class A is called and it displays "i from A is 60".
class A:
def __init__(self):
self.setI(20)
b = B()
A. The __init__ method of class A is not called.
B. The __init__ method of class A is called and it displays "i from B is 0".
C. The __init__ method of class A is called and it displays "i from B is 40".
D. The __init__ method of class A is called and it displays "i from B is 60".
13.6 To read the entire remaining contents of the file as a string from a file object infile, use
_________.
A. infile.read(2)
B. infile.read()
C. infile.readline()
D. infile.readlines()
13.7 To read the next line of the file from a file object infile, use _________.
A. infile.read(2)
B. infile.read()
C. infile.readline()
D. infile.readlines()
13.8 To read the remaining lines of the file from a file object infile, use _________.
A. infile.read(2)
B. infile.read()
C. infile.readline()
D. infile.readlines()
13.14 Invoking the ___________ method converts raw byte data to a string.
A. encode()
B. decode()
C. convert()
D. toString()
def main():
try:
f()
print("After the function call")
except ZeroDivisionError:
print("Divided by zero!")
except:
print("Exception")
def f():
print(1 / 0)
main()
A. "After the function call" followed by "Divided by zero!"
B. "After the function call"
C. "Divided by zero!"
D. "Divided by zero!" followed by "Exception"
try:
list = 10 * [0]
x = list[9]
print("Done")
except IndexError:
print("Index out of bound")
else:
print("Nothing is wrong")
finally:
print("Finally we are here")
A. "Done" followed by "Nothing is wrong"
B. "Done" followed by "Nothing is wrong" followed by "Finally we are here"
C. "Index out of bound" followed by "Nothing is wrong" followed by "Finally we are
here"
D. "Nothing is wrong" followed by "Finally we are here"
try:
list = 10 * [0]
x = list[10]
print("Done")
except IndexError:
print("Index out of bound")
else:
print("Nothing is wrong")
finally:
print("Finally we are here")
A. "Done" followed by "Nothing is wrong"
B. "Done" followed by "Nothing is wrong" followed by "Finally we are here"
C. "Index out of bound" followed by "Nothing is wrong" followed by "Finally we are
here"
D. "Nothing is wrong" followed by "Finally we are here"
E. "Index out of bound" followed by "Finally we are here"
13.21 Whihc function do you use to write data to perform binary output?
A. write
B. output
C. dump
D. send
13.22 Whihc function do you use to read data using binary input?
A. read
B. input
C. load
D. receive
14.4 Suppose t = (1, 2, 4, 3, 8, 9), [t[i] for i in range(0, len(t), 2)] is _________.
A. [2, 3, 9]
B. [1, 2, 4, 3, 8, 9]
C. [1, 4, 8]
D. (1, 4, 8)
E. (2, 3, 9)
14.5 Suppose t = (1, 2), 2 * t is _________.
A. (1, 2, 1, 2)
B. [1, 2, 1, 2]
C. (1, 1, 2, 2)
D. [1, 1, 2, 2]
E. illegal
@datascience-trainer
B. [1, 2, 1, 2]
C. (1, 1, 2, 2)
D. [1, 1, 2, 2]
E. illegal
14.31 Suppose d = {"john":40, "peter":45}, to delete the entry for "john":40, use ________.
A. d.delete("john":40)
B. d.delete("john")
C. del d["john"]
D. del d("john":40)
14.32 Suppose d = {"john":40, "peter":45}, to obtain the number of entries in dictionary, use
________.
A. d.size()
B. len(d)
C. size(d)
D. d.len()
d = {"john":40, "peter":45}
print(list(d.keys()))
A. ["john", "peter"]
B. ["john":40, "peter":45]
C. ("john", "peter")
D. ("john":40, "peter":45)
14.34 Suppose d = {"john":40, "peter":45}, what happens when retieving a value using
d["susan"]?
A. Since "susan" is not a value in the set, Python raises a KeyError exception.
B. It is executed fine and no exception is raised, and it returns None.
C. Since "susan" is not a key in the set, Python raises a KeyError exception.
D. Since "susan" is not a key in the set, Python raises a syntax error.
14.35 Suppose d = {"john":40, "peter":45}, what happens when retieving a value using
d.get("susan")?
A. Since "susan" is not a value in the set, Python raises a KeyError exception.
B. It is executed fine and no exception is raised, and it returns None.
C. Since "susan" is not a key in the set, Python raises a KeyError exception.
D. Since "susan" is not a key in the set, Python raises a syntax error.
14.36 Which of the following statements are true?
A. A Python list is immutable if every element in the list is immutable.
B. A Python set is immutable if every element in the set is immutable.
C. A Python tuple is immutable if every element in the tuple is immutable.
D. A Python tuple is immutable.
Chapter 15 Recursion
15.2 Fill in the code to complete the following function for computing factorial.
def factorial(n):
if n == 0: # Base case
return 1
else:
return _____________________ # Recursive call
A. n * (n - 1)
B. n
C. n * factorial(n - 1)
D. factorial(n - 1) * n
15.3 What are the base cases in the following recursive function?
def xfunction(n):
if n > 0:
print(n % 10)
xfunction(n // 10)
A. n > 0
B. n <= 0
C. no base cases
D. n < 0
def factorial(n):
return n * factorial(n - 1)
15.5 How many times is the factorial function in Listing 15.1 invoked for factorial(5)?
A. 3
B. 4
C. 5
D. 6
15.8 Fill in the code to complete the following function for computing a Fibonacci number.
def fib(index):
if index == 0: # Base case
return 0
elif index == 1: # Base case
return 1
else: # Reduction and recursive calls
return _________________________
A. fib(index - 1)
B. fib(index - 2)
C. fib(index - 1) + fib(index - 2)
D. fib(index - 2) + fib(index - 1)
Section 15.4 Problem Solving Using Recursion
15.9 In the following function, what is the base case?
def xfunction(n):
if n == 1:
return 1
else
return n + xfunction(n - 1)
A. n is 1.
B. n is greater than 1.
C. n is less than 1.
D. no base case.
15.10 What is the return value for xfunction(4) after calling the following function?
def xfunction(n):
if n == 1:
return 1;
else:
return n + xfunction(n - 1)
A. 12
B. 11
C. 10
D. 9
15.11 Fill in the code to complete the following function for checking whether a string is a
palindrome.
def isPalindrome(s):
if len(s) <= 1: # Base case
return True
elif _____________________________
return False
else:
return isPalindrome(s.substring(1, len(s) - 1))
A. s[0] != s[-1]: # Base case
B. s[0] != s[len(s)]: # Base case
C. s[1] != s[len(s) - 1]: # Base case
D. s[1] != s[len(s)]: # Base case
15.12 Analyze the following code:
x = [1, 2, 3, 4, 5]
xfunction(x, 5)
A. The program displays 1 2 3 4 6.
B. The program displays 1 2 3 4 5 and then raises an index out of range exception.
C. The program displays 5 4 3 2 1.
D. The program displays 5 4 3 2 1 and then raises an index out of range exception.
def isPalindrome(s):
return isPalindromeHelper(s, 0, len(s) - 1)
def isPalindromeHelper(s, low, high):
if high <= low: # Base case
return True
elif s[low] != s[high]: # Base case
return False
else:
return ____________________________
A. isPalindromeHelper(s)
B. isPalindromeHelper(s, low, high)
C. isPalindromeHelper(s, low + 1, high)
D. isPalindromeHelper(s, low, high - 1)
E. isPalindromeHelper(s, low + 1, high - 1)
15.14 Fill in the code to complete the following function for sorting a list.
def sort(lst):
_________________________ # Sort the entire list
def sortHelper(lst, low, high):
if low < high:
# Find the smallest number and its index in lst[low .. high]
indexOfMin = low
min = lst[low]
for i in range(low + 1, high + 1):
if lst[i] < min:
min = lst[i]
indexOfMin = i
# Swap the smallest in list(low .. high) with list(low)
lst[indexOfMin] = lst[low]
lst[low] = min
15.15 Fill in the code to complete the following function for binary search.
def main():
times = count("abcabc", 'a')
print(ch + " appears " + str(times) + (" times " if times > 1 else " time ") + "in " + s)
main()
A. a appears 1 times in abcdabc
B. a appears 2 times in abcdabc
C. a appears 1 time in abcdabc
D. a appears 2 time in abcdabc
15.18 How many times is the recursive moveDisks function invoked for 4 disks?
A. 5
B. 10
C. 15
D. 20
A:
def xfunction(length):
if length > 1:
print(length - 1, end = " ")
xfunction(length - 1)
xfunction(5)
B:
def xfunction(length):
while length > 1:
print(length - 1, end = " ")
xfunction(length - 1)
xfunction(5)
A. The two programs produce the same output 5 4 3 2 1.
B. The two programs produce the same output 1 2 3 4 5.
C. The two programs produce the same output 4 3 2 1.
D. The two programs produce the same output 1 2 3 4.
E. Program A produces the output 4 3 2 1 and Program B runs infinitely.
print(f1(3))
print(f2(3, 0))
A. f1 is tail recursion, but f2 is not
B. f2 is tail recursion, but f1 is not
C. f1 and f2 are both tail recursive
D. Neither f1 nor f2 is tail recursive
print(f2(2, 0))
A. 0
B. 1
C. 2
D. 3
16.2 An input that results in the shortest execution time is called the _____________.
A. best-case input
B. worst-case input
C. average-case input
16.3 Why is the analysis often for the worst case?
A. Best-case is not representative.
B. Worst-case is not representative, but worst-case analysis is very useful. You can show
that the algorithm will never be slower than the worst-case.
C. Average-case analysis is ideal, but difficult to perform, because it is hard to determine
the relative probabilities and distributions of various input instances for many problems.
16.4 Which of the following complexity is O(nlogn)
A. 300n + 400n*n
B. 23nlogn + 50
C. 45n + 45nlogn + 503
D. n*n*n + nlogn
16.9 The time complexity for the Towers of Honoi algorithm in the text is ________.
A. O(n)
B. O(n^2)
@datascience-trainer
C. O(n^3)
D. O(2^n)
16.10 The time complexity for the selection sort algorithm in the text is ________.
A. O(nlogn)
B. O(n^2)
C. O(logn)
D. O(2^n)
16.11 The time complexity for the insertion sort algorithm in the text is ________.
A. O(nlogn)
B. O(n^2)
C. O(logn)
D. O(2^n)
16.13 The time complexity for the recursive Fibnacci algorithm in the text is ________.
A. O(nlogn)
B. O(n^2)
C. O(logn)
D. O(2^n)
16.14 The time complexity for the algorithm using the dynamic programming approach is
________.
A. O(n)
B. O(n^2)
C. O(logn)
D. O(2^n)
Section 16.6 Finding Greatest Common Divisors Using Euclid?s Algorithm
16.15 The time complexity for the Euclid?s algorithm is ________.
A. O(n)
B. O(n^2)
C. O(logn)
D. O(2^n)
Section 16.7 Efficient Algorithms for Finding Prime Numbers
16.16 The time complexity for the Sieve of Eratosthenes algorithm is ________.
A. O(n)
B. O(n^(1.5)/logn)
C. O(logn)
D. O(2^n)
16.18 ______________ approach divides the problem into subproblems, solves the
subproblems, then combines the solutions of the subproblems to obtain the solution for the
entire problem. Unlike the ________ approach, the subproblems in the divide-and-conquer
approach don?t overlap. A subproblem is like the original problem with a smaller size, so you
can apply recursion to solve the problem.
A. Divide-and-conqure/dynamic programming
B. Dynamic programming/divide-and-conqure
C. Brutal-force/divide-and-conqure
D. Backtracking/dynamic programming
@datascience-trainer