Вы находитесь на странице: 1из 139

Question #1: what does the following code do?

def a(b, c, d): pass


defines a list and initializes it
defines a function, which does nothing - correct
defines a function, which passes its parameters through
defines an empty class

description: The 'def' statement defines a function. The 'pass' statement is a null operation.

Question #2: what gets printed? Assuming python version 2.x

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

Question #3: what is the output of the following code?

print type([1,2])
<type 'tuple'>
<type 'int'>
<type 'set'>
<type 'complex'>
<type 'list'> - correct
description: Lists are formed by placing a comma-separated list of expressions in square
brackets

Question #4: what gets printed?

def f(): pass


print type(f())
<type 'function'>
<type 'tuple'>
<type 'NoneType'> - correct
<type 'str'>
<type 'type'>
description: The argument to the type() call is a return value of a function call, which returns
None

Question #5: what should the below code print?

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

Question #6: what is the output of the following code?

print type(lambda:None)
<type 'NoneType'>
<type 'tuple'>
<type 'type'>
<type 'function'> - correct
<type 'bool'>
description: 'lambda arguments: expression' yields a function object

Question #7: what is the output of the below program?

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

Question #8: what gets printed? Assuming python version 3.x

print (type(1/2))
<type 'int'>
<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.

Question #9: What gets printed?

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.

Question #10: What gets printed?

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.

Question #11: What gets printed?

nums = set([1,1,2,3,3,3,4])
print len(nums)
1
2
4 - correct
5
7
description: nums is a set, so only unique values are retained.

Question #12: What gets printed?

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

Question #13: What gets printed?

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

Question #14: If PYTHONPATH is set in the environment, which directories are


searched for modules?

A) PYTHONPATH directory

B) current directory

C) home directory
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.

Question #17: Assuming python 2.6 what gets printed?

f = None

for i in range (5):


with open("data.txt", "w") as f:
if i > 2:
break

print f.closed
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.

Question #18: What gets printed?

counter = 1

def doLotsOfStuff():

global counter

for i in (1, 2, 3):


counter += 1

doLotsOfStuff()

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.

Question #19: What gets printed?

print r"\nwoow"
new line then the string: woow
the text exactly like this: r"\nwoow"
the text like exactly like this: \nwoow - correct
the letter r and then newline then the text: woow
the letter r then the text like this: nwoow
description: When prefixed with the letter 'r' or 'R' a string literal becomes a raw string and
the escape sequences such as \n are not converted.

Question #20: What gets printed?

print "hello" 'world'


on one line the text: hello world
on one line the text: helloworld - correct
hello on one line and world on the next line
syntax error, this python program will not run
description: String literals seperated by white space are allowed. They are concatenated.

Question #21: What gets printed?

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.

Question #22: What gets printed?

print 0xA + 0xa


0xA + 0xa
0xA 0xa
14
20 - correct
0x20
description: 0xA and 0xa are both hexadecimal integer literals representing the decimal value
10. Their sum is 20.

Question #23: What gets printed?

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.

Question #24: What gets printed?

kvps = {"user","bill", "password","hillary"}

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"}

Question #25: What gets printed?

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.

Question #26: What gets printed?

name = "snow storm"

print "%s" % name[6:8]


st
sto
to - correct
tor
Syntax Error
description: This is a slice of a string from index 6 to index 8 not including index 8. The first
character in the string is position 0.

Question #27: What gets printed?

name = "snow storm"

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

Question #28: Which numbers are printed?

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.

Question #29: What sequence of numbers is printed?

values = [1, 2, 1, 3]
nums = set(values)

def checkit(num):
if num in nums:
return True
else:
return False

for i in filter(checkit, values):


print i
123
1 2 1 3 - correct
12131213
11112233
Syntax Error
description: The filter will return all items from the list values which return True when
passed to the function checkit. checkit will check if the value is in the set. Since all the
numbers in the set come from the values list, all of the orignal values in the list will return
True.

Question #30: What sequence of numbers is printed?

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.

Question #31: What numbers get printed

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)

fd = open( "archive", "w" )


pickle.dump( myac, fd)
fd.close()

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.

Question #32: What gets printed by the code snippet below?

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.

Question #33: What gets printed by the code below?

class Person:
def __init__(self, id):
self.id = id

obama = Person(100)

obama.__dict__['age'] = 49

print obama.age + len(obama.__dict__)


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.

Question #34: What gets printed?

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

Question #35: What gets printed?

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.

Question #36: What does the code below do?

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

Question #37: What gets printed?

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']


print "\n".join(names) - correct
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

What gets printed?

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__".

Question #41: What gets printed

foo = {}
print type(foo)
set
dict - correct
list
tuple
object
description: Curly braces are the syntax for a dictionary declaration

Question #42: What gets printed?

foo = (3, 4, 5)
print type(foo)
int
list
tuple - correct
dict
set
description: Parentheses are used to initialize a tuple.

Question #43: What gets printed?

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.

Question #44: What gets printed?

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.

Question #45: What gets printed?

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.)"

Question #46: What gets printed?

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.

Question #47: What gets printed?

numberGames = {}
numberGames[(1,2,4)] = 8
numberGames[(4,2,1)] = 10
numberGames[(1,2)] = 12

sum = 0
for k in numberGames:
sum += numberGames[k]

print len(numberGames) + sum


8
12
24
30
33 - correct
description: Tuples can be used for keys into dictionary. The tuples can have mixed length
and the order of the items in the tuple is considered when comparing the equality of the keys.

Question #48: What gets printed?


foo = {1:'1', 2:'2', 3:'3'}
foo = {}
print len(foo)
0 - correct
1
2
3
An exception is thrown
description: after the second line of code, foo is an empty dictionary. The proper way to
actually remove all items from a dictionary is to call the 'clear' method of the dictionary object

Question #49: What gets printed?

foo = {1:'1', 2:'2', 3:'3'}


del foo[1]
foo[1] = '10'
del foo[2]
print len(foo)
1
2 - correct
3
4
An exception is thrown
description: The del function is used to remove key value pairs from a dictionary.

Question #50: What gets printed?

names = ['Amir', 'Barry', 'Chales', 'Dao']


print names[-1][-1]
A
r
Amir
Dao
o - correct
description: -1 refers to the last position in a list or the last character in a string. In this case,
we are referencing the last character in the last string in the list.

Question #51: What gets printed?

names1 = ['Amir', 'Barry', 'Chales', 'Dao']


names2 = names1
names3 = names1[:]

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.

Question #52: What gets printed?

names1 = ['Amir', 'Barry', 'Chales', 'Dao']

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.

Question #53: What gets printed?

names1 = ['Amir', 'Barry', 'Chales', 'Dao']

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.

Question #54: What gets printed?

names1 = ['Amir', 'Barry', 'Chales', 'Dao']


names2 = [name.lower() for name in names1]

print names2[2][0]
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.

Question #55: What gets printed?

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

Question #58: What gets printed?

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.

Question #59: What gets printed?

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.

Question #60: What gets printed?


a = 1
b = 2
a,b = b,a

print "%d %d" % (a,b)


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.

Question #61: What gets printed?

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))

+++1 some info+++ - correct


+++%s+++
1
1
some info
description: As of python 2.1 you could assign arbitrary typed information to functions.

Question #62: What gets printed?

def dostuff(param1, *param2):


print type(param2)

dostuff('apples', 'bananas', 'cherry', 'dates')


str
int
tuple - correct
list
dict
description: param2 aggregates remaining parameters into a tuple.
Question #63: What gets printed?

def dostuff(param1, **param2):


print type(param2)

dostuff('capitals', Arizona='Phoenix',
California='Sacramento', Texas='Austin')
in
str
tuple
list
dict - correct
description: param2 aggregates the remaining parameters into a dictionary.

Question #64: What gets printed?

def myfunc(x, y, z, a):


print x + y

nums = [1, 2, 3, 4]

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.

Question #67: What gets printed?

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)

Question #68: What gets printed?

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.

Question #69: Assuming python 2.x, what gets printed?

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.

Question #70: What gets printed?

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

Question #72: What gets printed?

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.

Question #74: What gets printed?

kvps = { '1' : 1, '2' : 2 }


theCopy = kvps

kvps['1'] = 5

sum = kvps['1'] + theCopy['1']


print sum
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.

Question #75: What gets printed?

kvps = { '1' : 1, '2' : 2 }


theCopy = kvps.copy()

kvps['1'] = 5

sum = kvps['1'] + theCopy['1']


print sum
1
2
6 - correct
10
An exception is thrown
description: The copy method of the dictionary will make a new (shallow) copy of the
dictionary so a change to the original in this case does not change the copy.

Question #76: What gets printed

aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }
theCopy = kvps.copy()

kvps['1'][0] = 5

sum = kvps['1'][0] + theCopy['1'][0]


print sum
1
2
6
10 - correct
An exception is thrown
description: The copy method provides a shallow copy therefore the list being held as the
value inside the dictionary is the same list in the copy as the original.

Question #77: What gets printed?

import copy

aList = [1,2]
bList = [3,4]

kvps = { '1' : aList, '2' : bList }


theCopy = copy.deepcopy(kvps)

kvps['1'][0] = 5

sum = kvps['1'][0] + theCopy['1'][0]


print sum
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.

Question #78: What gets printed?

kvps = { '1' : 1, '2' : 2 }


theCopy = dict(kvps)

kvps['1'] = 5

sum = kvps['1'] + theCopy['1']


print sum
1
2
6 - correct
10
An exception is thrown
description: Creating a new dictionary object initialized from the first does a 'shallow copy'

Question #79: What gets printed?

kvps = { '1' : 1, '2' : 2 , '3' : 3, '4' : 4, '5' : 5}


newData = { '1' : 10, '3' : 30 }

kvps.update(newData)

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.

Chapter 1 Introduction to Computers, Programs, and Python

Section 1.2 What is a Computer?


1.1  ________ is the physical aspect of the computer that can be seen.
A. Hardware
B. Software
C. Operating system
D. Application program

1.2  __________ is the brain of a computer.


A. Hardware
B. CPU
C. Memory
D. Disk

1.3  The speed of the CPU may be measured in __________.


A. megabytes
B. gigabytes
C. megahertz
D. gigahertz

1.4  Why do computers use zeros and ones?


A. because combinations of zeros and ones can represent any numbers and characters.
B. because digital devices have two stable states and it is natural to use one state for 0
and the other for 1.
C. because binary numbers are simplest.
D. because binary numbers are the bases upon which all other number systems are built.

1.5  One byte has ________ bits.


A. 4
B. 8
C. 12
D. 16

1.6  One gigabyte is approximately ________ bytes.


A. 1 million
B. 10 million
C. 1 billion
D. 1 trillion
1.7  A computer?s _______ is volatile; that is, any information stored in it is lost when the
system?s power is turned off.
A. floppy disk
B. hard disk
C. flash stick
D. CD-ROM
E. memory

1.8  Which of the following are storage devices?


A. floppy disk
B. hard disk
C. flash stick
D. CD-ROM

1.9  ____________ is a device to connect a computer to a local area network (LAN).


A. Regular modem
B. DSL
C. Cable modem
D. NIC

Section 1.3 Programs


1.10  ____________ are instructions to the computer.
A. Hardware
B. Software
C. Programs
D. Keyboards

1.11  Computer can execute the code in ____________.


A. machine language
B. assembly language
C. high-level language
D. none of the above

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.14  _____________ is a program that runs on a computer to manage and control a


computer's activities.
A. Operating system
B. Python
C. Modem
D. Interpreter
E. Compiler

Section 1.5 History of Python


1.15  Python was created by ____________.
A. James Gosling
B. Bill Gates
C. Steve Jobs
D. Guido van Rossum
E. Google

1.16  Which of the following statements is true?


A. Python 3 is a newer version, but it is backward compatible with Python 2.
B. Python 3 is a newer version, but it is not backward compatible with Python 2.
C. A Python 2 program can always run on a Python 3 interpreter.
D. A Python 3 program can always run on a Python 2 interpreter.

1.17  ________ is an object-oriented programming language.


A. Java
B. C++
C. C
D. C#
E. Python
1.18  ________ is interpreted.
A. Python
B. C++
C. C
D. Ada
E. Pascal

Section 1.6 Getting Started with Python


1.19  To start Python from the command prompt, use the command ________.
A. execute python
B. run python
C. python
D. go 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

1.21  Python syntax is case-sensitive.


A. True
B. False

1.22  Which of the following code is correct?

 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

Section 1.7 Programming Style and Documentation


1.23  A Python line comment begins with ________.
A. //
B. /*
C. #
D. $$

1.24  A Python paragraph comment uses the style ________.


A. // comments //
B. /* comments */
C. ''' comments '''
D. /# comments #/

Section 1.8 Programming Errors


1.25  A ___________ error does not cause the program to abort, but produces incorrect
results.
A. syntax
B. runtime
C. logic

1.26  In Python, a syntax error is detected by the ________ at _________.


A. compiler/at compile time
B. interpreter/at runtime
C. compiler/at runtime
D. interpreter/at compile time

1.27  Which of the following code is correct?

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

Section 1.9 Getting Started with Graphics Programming


1.28  To show the current location and direction of the turtle object, use ___________.
A. turtle.show()
B. turtle.showLocation()
C. turtle.showDirection()
D. turtle.showturtle()
E. turtle.showTurtle()

1.29  To move the turtle to a point at (4, 5), use ___________.


A. turtle.move(4, 5)
B. turtle.moveTo(4, 5)
C. turtle.moveto(4, 5)
D. turtle.go(4, 5)
E. turtle.goto(4, 5)

1.30  To draw a circle with radius 50, use ___________.


A. turtle.circle(50)
B. turtle.circle(100)
C. turtle.drawcircle(50)
D. turtle.drawCircle(50)

1.31  To lift the pen, use ___________.


A. turtle.penUp()
B. turtle.penup()
C. turtle.lift()
D. turtle.up()
1.32  To put the pen down, use ___________.
A. turtle.penDown()
B. turtle.pendown()
C. turtle.putDown()
D. turtle.down()

Chapter 2 Elementary Programming

Section 2.3 Reading Input from the Console


2.1  What function do you use to read a string?
A. input("Enter a string")
B. eval(input("Enter a string"))
C. enter("Enter a string")
D. eval(enter("Enter a string"))

2.2  What is the result of eval("1 + 3 * 2")?


A. "1 + 3 * 2"
B. 7
C. 8
D. "1 + 6"

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?

 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. The program runs correctly and displays 1.0
B. The program runs correctly and displays 2.0
C. The program runs correctly and displays 3.0
D. The program runs correctly and displays 4.0
E. The program will have a runtime error on the input.

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. &

Section 2.4 Identifiers


2.7  An identifier cannot be a keyword?
A. true
B. false

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

2.10  Which of the following is a valid identifier?


A. import
B. mile1
C. MILE
D. (red)
E. "red"

Section 2.5 Variables, Assignment Statements, and Expressions


2.11  If you enter 1, 2, 3, in one line, when you run this program, what will be displayed?

 number1, number2, number3 = eval(input("Enter three numbers: "))


 
 # Compute average
 average = (number1 + number2 + number3) / 3

 # Display result
 print(average)
A. 1.0
B. 2.0
C. 3.0
D. 4.0

2.12  What will be displayed by the following code?

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

Section 2.6 Simultaneous Assignments


2.14  What will be displayed by the following code?

x, y = 1, 2
x, y = y, x
print(x, y)
A. 1 1
B. 2 2
C. 1 2
D. 2 1

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,

Section 2.8 Numeric Data Types and Operators


2.16  What is the result of 45 / 4?
A. 10
B. 11
C. 11.25
D. 12

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

2.18  What is the result of 45 // 4?


A. 10
B. 11
C. 11.25
D. 12

2.19  Which of the following expressions will yield 0.5?


A. 1 / 2
B. 1.0 / 2
C. 1 // 2
D. 1.0 // 2
E. 1 / 2.0

2.20  Which of the following expression results in a value 1?


A. 2 % 1
B. 15 % 4
C. 25 % 5
D. 37 % 6

2.21  25 % 1 is _____
A. 1
B. 2
C. 3
D. 4
E. 0

2.22  24 % 5 is _____
A. 1
B. 2
C. 3
D. 4
E. 0

2.23  2 ** 3 evaluates to __________.


A. 9
B. 8
C. 9.0
D. 8.0

2.24  2 ** 3.0 evaluates to __________.


A. 9
B. 8
C. 9.0
D. 8.0

2.25  2 * 3 ** 2 evaluates to __________.


A. 36
B. 18
C. 12
D. 81

2.26  What is y displayed in the following code?

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

2.28  If a number is too large to be stored in memory, it _____________.


A. causes overflow
B. causes underflow
C. causes no error
D. cannot happen in Python

Section 2.9 Evaluating Expressions and Operator Precedence


2.29  What is the result of evaluating 2 + 2 ** 3 / 2?
A. 4
B. 6
C. 4.0
D. 6.0

Section 2.10 Augmented Assignment Operators


2.30  What is the value of i printed?

j = i = 1
i += j + j * 5
print("What is i?", i)
A. 0
B. 1
C. 5
D. 6
E. 7

2.31  What is x after the following statements?

x = 1
x *= x + 1
A. x is 1
B. x is 2
C. x is 3
D. x is 4

2.32  What is x after the following statements?

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

2.34  Which of the following statements are the same?

(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

2.35  To add number to sum, you write (Note: Python is case-sensitive)


A. number += sum
B. number = sum + number
C. sum = Number + sum
D. sum += number
E. sum = sum + number

2.36  Suppose x is 1. What is x after x += 2?


A. 0
B. 1
C. 2
D. 3
E. 4

2.37  Suppose x is 1. What is x after x -= 1?


A. 0
B. 1
C. 2
D. -1
E. -2
2.38  What is x after the following statements?

x = 1
y = 2
x *= y + 1
A. x is 1
B. x is 2
C. x is 3
D. x is 4

Section 2.11 Type Conversions and Rounding


2.39  Which of the following functions return 4.
A. int(3.4)
B. int(3.9)
C. round(3.4)
D. round(3.9)

2.40  Which of the following functions cause an error?


A. int("034")
B. eval("034")
C. int("3.4")
D. eval("3.4")

Section 2.12 Case Study: Displaying the Current Time


2.41  The time.time() returns ________________ .
A. the current time.
B. the current time in milliseconds.
C. the current time in milliseconds since midnight.
D. the current time in milliseconds since midnight, January 1, 1970.
E. the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix
time).

Chapter 3 Mathematical Functions, Strings, and Objects

Section 3.2 Common Python Functions


3.1  What is max(3, 5, 1, 7, 4)?
A. 1
B. 3
C. 5
D. 7
E. 4

3.2  What is min(3, 5, 1, 7, 4)?


A. 1
B. 3
C. 5
D. 7
E. 4

3.3  What is round(3.52)?


A. 3.5
B. 3
C. 5
D. 4
E. 3.0

3.4  What is round(6.5)?


A. 4
B. 5
C. 6
D. 7
E. 8

3.5  What is round(7.5)?


A. 4
B. 5
C. 6
D. 7
E. 8

3.6  Is pow(a, b) the same as a ** b?


A. Yes
B. No

3.7  What is math.degrees(math.pi / 2)?


A. 0.0
B. 90.0
C. 45.0
D. 30.0

3.8  What is math.radians(30) * 6?


A. 0.0
B. 1.3434343
C. 3.141592653589793
D. 5.565656

3.9  What is math.sin(math.pi / 6)?


A. 1.0
B. 1.3434343
C. 3.141592653589793
D. 0.5

Section 3.3 Strings and Characters


3.10  Which of the following is the correct expression of character 4?
A. 4
B. "4"
C. '4'

3.11  In Python, a string literal is enclosed in __________.


A. parentheses
B. brackets
C. single-quotes
D. double-quotes
E. braces

3.12  What is chr(ord('B')))?


A. A
B. B
C. C
D. D

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.14  Which of the following statement prints smith\exam1\test.txt?


A. print("smith\exam1\test.txt")
B. print("smith\\exam1\\test.txt")
C. print("smith\"exam1\"test.txt")
D. print("smith"\exam1"\test.txt")

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.17  Will print(chr(4)) display 4?


A. Yes
B. No

3.18  What will be displayed by print(ord('z') - ord('a'))?


A. 25
B. 26
C. a
D. z

3.19  The expression "Good " + 1 + 2 + 3 evaluates to ________.


A. Good123
B. Good6
C. Good 123
D. Illegal expression

3.20  What will be displayed by the following code?

print("A", end = ' ')
print("B", end = ' ')
print("C", end = ' ')
print("D", end = ' ')
A. ABCD
B. A, B, C, D
C. A B C D
D. A, B, C, D will be displayed on four lines

3.21  Which of the following statements is correct?


A. s = "Chapter " + 1
B. s = "Chapter " + str(1)

Section 3.5 Introduction to Objects and Methods


3.22  What is the type for object 5.6?
A. int
B. float
C. str

3.23  Which of the following statements are true?


A. Each object has a unique id.
B. Objects of the same type have the same id.
C. Objects of the same kind have the same type.
D. A variable that holds a value is actually a reference to an object for the value.

3.24  Suppose s = "Welcome", what is type(s)?


A. int
B. float
C. str
D. String

3.25  Suppose s is "Welcome", what is s.upper()?


A. welcome
B. WELCOME
C. Welcome
3.26  Suppose s is "\t\tWelcome\n", what is s.strip()?
A. \t\tWelcome\n
B. \t\tWelcome\n
C. \t\tWELCOME\n
D. welcome

Section 3.6 Formatting Numbers and Strings


3.27  The format function returns _______.
A. an int
B. a float
C. a str

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)

  print(format("Welcome", "10s"), end = '#')


  print(format(111, "4d"), end = '#')
  print(format(924.656, "3.2f"))
A. ???Welcome#?111#924.66
B. Welcome#111#924.66
C. Welcome#111#.66
D. Welcome???#?111#924.66

3.31  What will be displayed by the following code? ? (note ? represents a blank space)

  print(format("Welcome", ">10s"), end = '#')


  print(format(111, "<4d"), end = '#')
  print(format(924.656, ">10.2f"))
A. ???Welcome#?111#924.66
B. ???Welcome#?111#????924.66
C. ???Welcome#111?#????924.66
D. Welcome???#111?#????924.66

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"))

Section 3.7 Drawing Various Shapes


3.33  To set the pen size to 5 pixels, use _________.
A. turtle.setSize(5)
B. turtle.size(5)
C. turtle.pensize(5)
D. turtle.setPenSize(5)

3.34  To undo the last turtle action, use _________.


A. turtle.rollback()
B. turtle.redo()
C. turtle.undo()
D. turtle.remove()

3.35  To set a turtle drawing speed to 5, use _________.


A. turtle.speed(5)
B. turtle.setSpeed(5)
C. turtle.setspeed(5)
D. turtle.velocity(5)

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

Section 4.2 Boolean Types, Values, and Expressions


4.1  The "less than or equal to" comparison operator is __________.

A. <
B. <=
C. =<
D. <<
E. !=

4.2  The equal comparison operator is __________.


A. <>
B. !=
C. ==
D. =

4.3  The word True is ________.


A. a Python keyword
B. a Boolean literal
C. same as value 1
D. same as value 0

Section 4.3 Generating Random Numbers


4.4  To generate a random integer between 0 and 5, use ________________.
A. random.randint(0, 5)
B. random.randint(0, 6)
C. random.randrange(0, 5)
D. random.randrange(0, 6)

4.5  random.randint(0, 1) returns ____________.


A. 0
B. 1
C. 0 or 1
D. 2

4.6  random.random() returns ____________.


A. a float number i such that 0 < i < 1.0
B. a float number i such that 0 <= i < 1.0
C. a float number i such that 0 <= i <= 1.0
D. a float number i such that 0 < i < 2.0

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)

4.8  What is the output of the following code?

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:

4.10  Analyze the following code:

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!.

4.11  Analyze the following code.

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

4.13  The following code displays ___________.

temperature = 50

if temperature >= 100:
    print("too hot")
elif temperature <= 40:
    print("too cold")
else:
    print("just right")
A. too hot
B. too cold
C. just right
D. too hot too cold just right

4.14  Analyze the following code:

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?

if income > 3000:
    print("Income is greater than 3000")
elif income > 4000:
    print("Income is greater than 4000")
A. none
B. Income is greater than 3000
C. Income is greater than 3000 followed by Income is greater than 4000
D. Income is greater than 4000
E. Income is greater than 4000 followed by Income is greater than 3000

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.18  The __________ function immediately terminates the program.


A. sys.terminate()
B. sys.halt()
C. sys.exit()
D. sys.stop()

Section 4.11 Logical Operators


4.19  Which of the Boolean expressions below is incorrect?
A. True and 3 => 4
B. !(x > 0) and (x > 0)
C. (x > 0) or (x < 0)
D. (x != 0) or (x = 0)
E. (-10 < x < 0)

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')

4.21  Given |x - 2| <= 4, Which of the following is true?


A. x - 2 <= 4 and x - 2 >= 4
B. x - 2 <= 4 and x - 2 > -4
C. x - 2 <= 4 and x - 2 >= -4
D. x - 2 <= 4 or x - 2 >= -4

4.22  Given |x - 2| >= 4, Which of the following is true?


A. x - 2 >= 4 and x - 2 <= -4
B. x - 2 >= 4 or x - 2 <= -4
C. x - 2 >= 4 and x - 2 < -4
D. x - 2 >= 4 or x - 2 <= -4

4.23  Assume x = 4 and y = 5, Which of the following is true?


A. x < 5 and y < 5
B. x < 5 or y < 5
C. x > 5 and y > 5
D. x > 5 or y > 5

4.24  Assume x = 4 and y = 5, Which of the following is true?


A. not (x == 4)
B. x != 4
C. x == 5
D. x != 5

4.25  Assume x = 14 and y = 15, Which of the following is true?


A. x % 2 == 0 and y % 2 == 0
B. x % 2 == 0 and y % 2 == 1
C. x % 2 == 0 or y % 2 == 0
D. x % 2 != 0 and y % 2 != 0

4.26  Which of the following is equivalent to x != y?


A. not (x == y)
B. x > y and x < y
C. x > y or x < y
D. x >= y or x <= y

4.27  What will be displayed by the following code?

ch = 'F'
if ch >= 'A' and ch <= 'Z':
    print(ch)
A. F
B. f
C. nothing
D. F f

Section 4.14 Conditional Expressions


4.28  What is y after the following statement is executed?
x = 0
y = 10 if x > 0 else -10
A. -10
B. 0
C. 10
D. 20
E. Illegal expression

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

Section 4.15 Operator Precedence and Associativity


4.31  The order of the precedence (from high to low) of the operators +, *, and, or is:
A. and, or, *, +
B. *, +, and, or
C. *, +, and, or
D. *, +, or, and
E. or, and, *, +

4.32  Which of the following operators are right-associative.


A. *
B. +
C. %
D. and
E. =

4.33  What is the value of the following expression?

True or True and False
A. True
B. False

4.34  Which of the following statements are True?


A. (x > 0 and x < 10) is same as (x > 0 and x < 10)
B. (x > 0 or x < 10) is same as (0 < x < 10)
C. (x > 0 or x < 10 and y < 0) is same as (x > 0 or (x < 10 and y < 0))
D. (x > 0 or x < 10 and y < 0) is same as ((x > 0 or x < 10) and y < 0)

Chapter 5 Loops

Section 5.2 The while Loop


5.1  How many times will the following code print "Welcome to Python"?

count = 0
while count < 10:
    print("Welcome to Python")
    count += 1
A. 8
B. 9
C. 10
D. 11
E. 0
5.2  What is the output of the following code?

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

5.3  Analyze the following code.

 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

Section 5.3 The for Loop


5.6  Analyze the following statement:

sum = 0
for d in range(0, 10, 0.1):
    sum += sum + d
A. The program has a syntax error because the range function cannot have three
arguments.
B. The program has a syntax error because the arguments in the range must be integers.
C. The program runs in an infinite loop.
D. The program runs fine.

5.7  Which of the following loops prints "Welcome to Python" 10 times?

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.8  The function range(5) return a sequence ______________.


A. 1, 2, 3, 4, 5
B. 0, 1, 2, 3, 4, 5
C. 1, 2, 3, 4
D. 0, 1, 2, 3, 4

5.9  Which of the following function returns a sequence 0, 1, 2, 3?


A. range(0, 3)
B. range(0, 4)
C. range(3)
D. range(4)

5.10  Which of the following function is incorrect?


A. range(0, 3.5)
B. range(10, 4, -1)
C. range(1, 3, 1)
D. range(2.5, 4.5)
E. range(1, 2.5, 4.5)

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

5.12  The following loop displays _______________.

for i in range(1, 11):
    print(i, end = " ")
A. 1 2 3 4 5 6 7 8 9
B. 1 2 3 4 5 6 7 8 9 10
C. 1 2 3 4 5
D. 1 3 5 7 9
E. 2 4 6 8 10

5.13  What is the output for y?

y = 0
for i in range(0, 10):
    y += i

print(y)
A. 10
B. 11
C. 12
D. 13
E. 45

5.14  What is the output for y?

y = 0
for i in range(0, 10, 2):
    y += i
print(y)
A. 9
B. 10
C. 11
D. 20

5.15  What is the output for y?

y = 0
for i in range(10, 1, -2):
    y += i

print(y)
A. 10
B. 40
C. 30
D. 20

5.16  Given the following four patterns,

Pattern A        Pattern B        Pattern C        Pattern D
1                1 2 3 4 5 6                1      1 2 3 4 5 6
1 2              1 2 3 4 5                2 1        1 2 3 4 5
1 2 3            1 2 3 4                3 2 1          1 2 3 4
1 2 3 4          1 2 3                4 3 2 1            1 2 3
1 2 3 4 5        1 2                5 4 3 2 1              1 2
1 2 3 4 5 6      1                6 5 4 3 2 1                1

Which of the pattern is produced by the following code?

for i in range(1, 6 + 1):
    for j in range(6, 0, -1):
       print(j if j <= i else " ", end = " ")
    print()
A. Pattern A
B. Pattern B
C. Pattern C
D. Pattern D

Section 5.5 Minimizing Numerical Errors


5.17  Analyze the following fragment:
sum = d = 0
while d != 10.0:
    d += 0.1
    sum += sum + d
A. The program does not run because sum and d are not initialized correctly.
B. The program never stops because d is always 0.1 inside the loop.
C. The program may not stop because of the phenomenon referred to as numerical
inaccuracy for operating with floating-point numbers.
D. After the loop, sum is 0 + 0.1 + 0.2 + 0.3 + ... + 1.9

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

5.20  How many times is the print statement executed?

for i in range(10): 
    for j in range(i):
        print(i * j)
A. 100
B. 20
C. 10
D. 45

Section 5.7 Keywords break and continue


5.21  Will the following program terminate?

balance = 10

while True:
    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

5.23  What is sum after the following loop terminates?

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

5.24  Will the following program terminate?

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

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.26  What will be displayed by after the following loop terminates?

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.27  What is the number of iterations in the following loop:

  for i in range(1, n):


      # iteration
A. 2*n
B. n
C. n - 1
D. n + 1
5.28  What is the number of iterations in the following loop:

  for i in range(1, n + 1):


      # iteration
A. 2*n
B. n
C. n - 1
D. n + 1

5.29  Suppose the input for number is 9. What will be displayed by the following program?

number = eval(input("Enter an integer: "))

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

Sections 6.2 Defining a Function


6.1  If a function does not return a value, by default, it returns ___________.
A. None
B. int
C. double
D. public
E. null

6.2  The header of a function consists of ____________.


A. function name
B. function name and parameter list
C. parameter list

6.3  A function _________.


A. must have at least one parameter
B. may have no parameters
C. must always have a return statement to return a value
D. must always have a return statement to return multiple values

Sections 6.3 Calling a Function


6.4  Arguments to functions always appear within __________.
A. brackets
B. parentheses
C. curly braces
D. quotation marks

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

Sections 6.4 Functions With/Without Return Values


6.7  Which of the following should be defined as a None function?
A. Write a function that prints integers from 1 to 100.
B. Write a function that returns a random integer from 1 to 100.
C. Write a function that checks whether current second is an integer from 1 to 100.
D. Write a function that converts an uppercase letter to lowercase.
6.8  A function with no return statement returns ______.
A. void
B. nothing
C. 0
D. None

6.9  Consider the following incomplete code:

def f(number):
  # Missing function body

print(f(5))

The missing function body should be ________.
A. return "number"
B. print(number)
C. print("number")
D. return number

Sections 6.5 Positional and Keyword Arguments


6.10  Given the following function header:

def f(p1, p2, p3, p4)

Which of the following is correct to invoke it?
A. f(1, 2, 3, 4)
B. f(p1 = 1, 2, 3, 4)
C. f(p1 = 1, p2 = 2, p3 = 3, 4)
D. f(p1 = 1, p2 = 2, p3 = 3, p4 = 4)
E. f(1, 2, 3, p4 = 4)

6.11  Given the following function

def nPrint(message, n):
    while n > 0:
        print(message)
        n -= 1

What will be displayed by the call nPrint('a', 4)?

A. aaaaa
B. aaaa
C. aaa
D. invalid call
E. infinite loop

6.12  Given the following function

def nPrint(message, n):
    while n > 0:
        print(message)
    n -= 1

What will be displayed by the call nPrint('a', 4)?
A. aaaaa
B. aaaa
C. aaa
D. invalid call
E. infinite loop

6.13  Given the following function

def nPrint(message, n):
    while n > 0:
        print(message)
        n -= 1

What is k after invoking nPrint("A message", k)?

k = 2
nPrint("A message", k)
A. 0
B. 1
C. 2
D. 3

6.14  Given the following function

def nPrint(message, n):
    while n > 0:
        print(message)
        n -= 1

What is k after invoking nPrint("A message", k)?
k = 2
nPrint(n = k, message = "A message")
A. 0
B. 1
C. 2
D. 3

Sections 6.6 Passing Parameters by Values


6.15  When you invoke a function with a parameter, the value of the argument is passed to
the parameter. This is referred to as _________.
A. function invocation
B. pass by value
C. pass by reference
D. pass by name

Section 6.9 The Scope of Variables


6.16  A variable defined inside a function is referred to as __________.
A. a global variable
B. a function variable
C. a block variable
D. a local variable

6.17  A variable defined outside a function is referred to as __________.


A. a global variable
B. a function variable
C. a block variable
D. a local variable

6.18  Whenever possible, you should avoid using __________.


A. global variables
B. function parameters
C. global constants
D. local variables

6.19  What will be displayed by the following code?

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

6.20  What will be displayed by the following code?

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

6.21  What will be displayed by the following code?

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

6.22  What will be displayed by the following code?

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

Section 6.10 Default Arguments


6.23  What will be displayed by the following code?

def f1(x = 1, y = 2):
    x = x + y
    y += 1
    print(x, y)

f1()
A. 1 3
B. 3 1
C. The program has a runtime error because x and y are not defined.
D. 1 1
E. 3 3

6.24  What will be displayed by the following code?

def f1(x = 1, y = 2):
    x = x + y
    y += 1
    print(x, y)

f1(2, 1)
A. 1 3
B. 2 3
C. The program has a runtime error because x and y are not defined.
D. 3 2
E. 3 3

6.25  What will be displayed by the following code?


def f1(x = 1, y = 2):
    x = x + y
    y += 1
    print(x, y)

f1(y = 2, x = 1)
A. 1 3
B. 2 3
C. The program has a runtime error because x and y are not defined.
D. 3 2
E. 3 3

6.26  Which of the following function headers is correct?


A. def f(a = 1, b):
B. def f(a = 1, b, c = 2):
C. def f(a = 1, b = 1, c = 2):
D. def f(a = 1, b = 1, c = 2, d):

Section 6.11 Returning Multiple Values


6.27  What will be displayed by the following code?

def f1(x = 1, y = 2):
    return x + y, x - y

x, y = f1(y = 2, x = 1)
print(x, y)
A. 1 3
B. 3 1
C. The program has a runtime error because the function returns the multiple values
D. 3 -1
E. -1 3

Section 6.13 Function Abstraction and Stepwise Refinement


6.28  __________ is to implement one function in the structure chart at a time from the top to
the bottom.
A. Bottom-up approach
B. Top-down approach
C. Bottom-up and top-down approach
D. Stepwise refinement

6.29  __________ is a simple but incomplete version of a function.


A. A stub
B. A function
C. A function developed using botton-up approach
D. A function developed using top-down approach

Chapter 7 Objects and Classes

Section 7.2 Defining Classes for Objects


7.1  __________ represents an entity in the real world that can be distinctly identified.
A. A class
B. An object
C. A method
D. A data field

7.2  _______ is 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

7.3  An object is an instance of a __________.


A. program
B. class
C. method
D. data

7.4  The keyword __________ is required to define a class.


A. def
B. return
C. class
D. All of the above.

7.5  ________ is used to create an object.


A. A constructor
B. A class
C. A value-returning method
D. A None method

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

7.7  Analyze the following code:

 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).

7.8  Analyze the following code:

 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.

7.9  Analyze the following code:


 class A:
     def __init__(self, s = "Welcome"):
         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.
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.

Section 7.4 Hiding Data Fields


7.11  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.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.

7.13  Analyze the following code:

 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.

7.14  In the following code,

 def A:
 def __init__(self):
     __a = 1
     self.__b = 1
     self.__c__ = 1
     __d__ = 1

 # Other methods omitted

Which of the following is a private data field?
A. __a
B. __b
C. __c__
D. __d__

7.15  Analyze the following code:

 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.

7.16  Which of the following statement is most accurate?

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 may contain the references of other objects.

7.17  What is the value of times displayed?

def main():
    myCount = Count()
    times = 0

    for i in range(0, 100):


        increment(myCount, times)

    print("myCount.count =", myCount.count, "times =", times)

def increment(c, times):
    c.count += 1
    times += 1

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

Chapter 8 More on Strings and Special Methods

Section 8.2 The str Class


8.1  What is len("Good")?
A. 1
B. 2
C. 3
D. 4
E. -1

8.2  What is max("Programming is fun")?


A. P
B. r
C. a blank space character
D. u
E. n

8.3  What is min("Programming is fun")?


A. P
B. r
C. a blank space character
D. u
E. n

8.4  What is "Programming is fun"[4: 6]?


A. ram
B. ra
C. r
D. pr
E. pro

8.5  What is "Programming is fun"[-1]?


A. Pr
B. P
C. fun
D. n
E. un

8.6  What is "Programming is fun"[1:1]?


A. P
B. r
C. Pr
D. ''
E. incorrect expression

8.7  What is "Programming is fun"[-3:-1]?


A. Pr
B. P
C. fun
D. un
E. fu

8.8  What is "Programming is fun"[:-1]?


A. Programming
B. rogramming is fun
C. Programming is f
D. Programming is fu
E. Programming is

8.9  What is "Programming is fun"[:2]?


A. Pr
B. P
C. Pro
D. Programming
E. Programming is

8.10  Given a string s = "Welcome", which of the following code is incorrect?


A. print(s[0])
B. print(s.lower())
C. s[1] = 'r'
D. print(s.strip())

8.11  What will be displayed by the following code?

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

8.12  Given a string s = "Welcome", what is s.count('e')?


A. 1
B. 2
C. 3
D. 4
8.13  Given a string s = "Programming is fun", what is s.find('ram')?
A. 1
B. 2
C. 3
D. 4
E. -1

8.14  Given a string s = "Programming is fun", what is s.find('rom')?


A. 1
B. 2
C. 3
D. 4
E. -1

8.15  Given a string s = "Programming is fun", what is s.rfind('m')?


A. 8
B. 7
C. 6
D. 5
E. -1

8.16  Given a string s = "Programming is fun", what is s.find('m')?


A. 8
B. 7
C. 6
D. 5
E. -1

8.17  Given a string s = "Programming is fun", what is s.startswith('m')?


A. 0
B. 1
C. -1
D. True
E. False

8.18  Given a string s = "Programming is fun", what is s.startswith('Program')?


A. 0
B. 1
C. -1
D. True
E. False

8.19  Given a string s = "Programming is fun", what is s.endswith('fun')?


A. 0
B. 1
C. -1
D. True
E. False

8.20  Given a string s = "Programming is fun", what is s.endswith('m')?


A. 0
B. 1
C. -1
D. True
E. False

8.21  What is "Good".replace("o", "e")?


A. God
B. Good
C. Geed
D. Ged
E. Good

8.22  Analyze the following code:

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)
A. The program displays Peter Pan.
B. The program displays John Pan.
C. The program displays Peter Smith.
D. The program displays John Smith.

8.23  Analyze the following code:

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.

Section 8.5 Operator Overloading and Special Methods


8.24  To concatenate two strings s1 and s2 into s3, use _________.
A. s3 = s1 + s2
B. s3 = s1.add(s2)
C. s3 = s1.__add(s2)
D. s3 = s1.__add__(s2)

8.25  To retrieve the character at index 3 from string s, use _________.


A. s[3]
B. s.getitem(3)
C. s.__getitem__(3)
D. s.getItem(3)
8.26  To return the length of string s, use _________.
A. s.__len__()
B. len(s)
C. size(s)
D. s.size()

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)

8.28  To check whether string s1 contains s2, use _________.


A. s1.__contains__(s2)
B. s1 in s2
C. s1.contains(s2)
D. si.in(s2)

8.29  Suppose i is 2 and j is 4, i + j is same as _________.


A. i.__add(j)
B. i.__add__(j)
C. i.__Add(j)
D. i.__ADD(j)

Chapter 9 GUI Programming Using Tkinter

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.3  How do you create an event loop?


A. window.loop()
B. window.main()
C. window.mainloop()
D. window.eventloop()

9.4  To create a label under parent window, use _______.


A. label = Label(text = "Welcome to Python")
B. label = Label(window, text = "Welcome to Python")
C. label = Label(text = "Welcome to Python", fg = " red")
D. label = Label(text = "Welcome to Python", fg = " red", bg = "white")

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.6  Assume v1 = IntVar(), how do you set a new value 5 to v1.


A. v1 = 5
B. v1.setValue(5)
C. v1.set(5)
D. v1.get(5)

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

9.11  How do you create a text area?


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")

Section 9.6 The Geometry Managers


9.19  _______ are geometry managers in Tkinter.
A. pack
B. grid
C. place
D. flow

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.22  The side option of the pack manager may be _____________.


A. LEFT
B. RIGHT
C. BOTTOM
D. TOP

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

Section 9.8 Displaying Images


9.24  To create an image, use ______________________.
A. image = PhotoImage(imagefilename)
B. image = Image(file = imagefilename)
C. image = PhotoImage(file = imagefilename)
D. image = PhotoImage(imagefilename)
9.25  You can create an image from a ____________ file.
A. .png
B. .gif
C. .bmp
D. .jpg

9.26  You can display an image in ______________.


A. a label
B. a button
C. a check button
D. a radio button
E. an entry

Section 9.9 Menus


9.27  To create a menu in a window, use __________
A. menubar = Menu(window)
B. menubar = MenBar(window)
C. menubar = Menu()
D. menubar = MenBar()

9.28  To add a menu in a menubar, use __________


A. menu1 = Menu(menubar)
B. menu1 = menu(menubar)
C. menu1 = Menu(winodw)
D. menu1 = Menu()

9.29  To add a menubar, use __________


A. window.configure(menu = menubar)
B. window.config(menubar)
C. window.config(menu = menubar)
D. window.configure(menubar)

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.33  To bind a canvas with a mouse entered event p, use __________


A. canvas.entered(p)
B. canvas.bind("<Enter>", p)
C. canvas.bind("<Entered>", p)
D. canvas.bind(<Enter>, 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.37  To bind a canvas with a key event p, use __________


A. canvas.entered(p)
B. canvas.bind("<Enter>", p)
C. canvas.bind("<Key>", p)
D. canvas.bind(<Enter>, p)
E. canvas.bind("<Enter>", p)

9.38  The mouse event object has the property ____________.


A. x
B. y
C. widget
D. X
E. Y

Section 9.14 Standard Dialogs


9.39  To display a message dialog named "Programming is fun", use __________
A. tkinter.messagebox.showinfo("showinfo", "Programming is fun")
B. tkinter.messagebox.showwarning("showwarning", "Programming is fun")
C. tkinter.messagebox.showerror("showerror", "Programming is fun")
D. tkinter.messagebox.askyesno("ashyesno", "Programming is fun")

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.42  To 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

Section 10.2 List Basics


10.1  __________ creates a list.
A. list1 = list()
B. list1 = []
C. list1 = list([12, 4, 4])
D. list1 = [12, 4, 4]
E. list1 = [1, "3", "red"]

10.2  What is list("abcd")?


A. ['a', 'b', 'c', 'd']
B. ['ab']
C. ['cd']
D. ['abcd']

10.3  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is len(list1)?


A. 6
B. 7
C. 8
D. 5
E. 4

10.4  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is max(list1)?


A. 5
B. 4
C. 8
D. 25
E. 1
10.5  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is min(list1)?
A. 5
B. 4
C. 8
D. 25
E. 1

10.6  Suppose list1 is [1, 3, 2], what is sum(list1)?


A. 5
B. 4
C. 6
D. 2
E. 1

10.7  To shuffle list1, use _______.


A. list1.shuffle()
B. shuffle(list1)
C. random.shuffle(list1)
D. random.shuffleList(list1)

10.8  Suppose list1 is [1, 3, 2, 4, 5, 2, 1, 0], Which of the following is correct?


A. print(list1[0])
B. print(list1[:2])
C. print(list1[:-2])
D. print(list1[4:6])

10.9  Suppose list1 is [1, 3, 2, 4, 5, 2, 1, 0], What is list1[-1]?


A. 3
B. 5
C. 1
D. 0

10.10  Suppose list1 is [1, 3, 2, 4, 5, 2, 1, 0], What is list1[:-1]?


A. 0
B. [1, 3, 2, 4, 5, 2, 1]
C. [1, 3, 2, 4, 5, 2]
D. [1, 3, 2, 4, 5, 2, 1, 0]

10.11  Suppose list1 is [1, 3, 2], What is list1 * 2?


A. [2, 6, 4]
B. [1, 3, 2, 1, 3]
C. [1, 3, 2, 1, 3, 2]
D. [1, 3, 2, 3, 2, 1]

10.12  Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is ________


A. [0, 1, 2, 3]
B. [0, 1, 2, 3, 4]
C. [0.0, 0.5, 1.0, 1.5]
D. [0.0, 0.5, 1.0, 1.5, 2.0]

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

10.15  To add 5 to the end of list1, use _______.


A. list1.add(5)
B. list1.append(5)
C. list1.addLast(5)
D. list1.addEnd(5)

10.16  To insert 5 to the third position in list1, use _______.


A. list1.insert(3, 5)
B. list1.insert(2, 5)
C. list1.add(3, 5)
D. list1.append(3, 5)

10.17  To remove string "red" from list1, use _______.


A. list1.remove("red")
B. list1.remove(red)
C. list1.removeAll("red")
D. list1.removeOne("red")

10.18  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.index(5)?


A. 0
B. 4
C. 1
D. 2

10.19  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5)?


A. 0
B. 4
C. 1
D. 2

10.20  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.sort()?
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]

10.21  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.reverse()?
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]

10.22  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.extend([34, 5])?
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]

10.23  Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.pop(1)?
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]

10.25  "Welcome to Python".split() is ________


A. ["Welcome", "to", "Python"]
B. ("Welcome", "to", "Python")
C. {"Welcome", "to", "Python"}
D. "Welcome", "to", "Python"

10.26  What is list("a#b#c#d".split('#')?


A. ['a', 'b', 'c', 'd']
B. ['a b c d']
C. ['a#b#c#d']
D. ['abcd']

10.27  What will be displayed by the following code?

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]

for i in range(0, 6): 
    print(myList[i], end = " ")
A. 2 3 4 5 6 1
B. 6 1 2 3 4 5
C. 2 3 4 5 6 6
D. 1 1 2 3 4 5
E. 2 3 4 5 6 1

Section 10.6 Copying Lists


10.29  What will be displayed by the following code?

list1 = [1, 3]
list2 = list1
list1[0] = 4
print(list2)
A. [1, 3]
B. [4, 3]
C. [1, 4]
D. [1, 3, 4]

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]

10.31  What will be displayed by the following code?

def f(value, values):
    v = 1
    values[0] = 44

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

10.32  What will be displayed by the following code?

def f(i, values = []):
    values.append(i)
    return values

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

Section 10.10 Searching Lists


10.33  For the binarySearch function in Section 10.10.2, what is low and high after the first
iteration of the while loop when invoking binarySearch([1, 4, 6, 8, 10, 15, 20], 11)?
A. low is 0 and high is 6
B. low is 0 and high is 3
C. low is 3 and high is 6
D. low is 4 and high is 6
E. low is 0 and high is 5

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

Chapter 11 Multidimensional Lists

11.1  What will be displayed by the following code?

m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(m[0][0])
A. 1
B. 2
C. 4
D. 7

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

11.4  For m = [[x, x + 1, x + 2] for x in range(0, 3)], m is _______.


A. [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B. [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
C. [1, 2, 3, 4, 5, 6, 7, 8, 9]
D. [0, 1, 2, 1, 2, 3, 2, 3, 4]

11.5  For m = [[x, x + 1, x + 2] for x in range(1, 9, 3)], m is _______.


A. [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B. [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
C. [1, 2, 3, 4, 5, 6, 7, 8, 9]
D. [0, 1, 2, 1, 2, 3, 2, 3, 4]

11.6  How many elements are in m = [[x, y] for x in range(0, 4) for y in range(0, 4)]?
A. 8
B. 12
C. 16
D. 32

11.7  Assume x = ((1, 2), (3, 4, 5), (5, 6, 5, 9)), what are len(x) are len(x[0])?
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

11.9  What will be displayed by the following program?

values = [[3, 4, 5, 1], [33, 6, 1, 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

11.10  What will be displayed by the following program?

values = [[3, 4, 5, 1], [33, 6, 1, 2]]

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?

values = [[3, 4, 5, 1 ], [33, 6, 1, 2]]

for row in values:
    row.sort()
    for element in row:
        print(element, end = " ")
    print()
A. The program prints two rows 3 4 5 1 followed by 33 6 1 2
B. The program prints on row 3 4 5 1 33 6 1 2
C. The program prints two rows 3 4 5 1 followed by 33 6 1 2
D. The program prints two rows 1 3 4 5 followed by 1 2 6 33
E. The program prints one row 1 3 4 5 1 2 6 33

11.12  What will be displayed by the following code?

matrix = [[1, 2, 3, 4],
       [4, 5, 6, 7],
       [8, 9, 10, 11],
       [12, 13, 14, 15]]

for i in range(0, 4):
    print(matrix[i][1], end = " ")
A. 1 2 3 4
B. 4 5 6 7
C. 1 3 8 12
D. 2 5 9 13
E. 3 6 10 14

11.13  What will be displayed by the following code?

matrix = [[1, 2, 3, 4],
       [4, 5, 6, 7],
       [8, 9, 10, 11],
       [12, 13, 14, 15]]

for i in range(0, 4):
    print(matrix[1][i], end = " ")
A. 1 2 3 4
B. 4 5 6 7
C. 1 3 8 12
D. 2 5 9 13
E. 3 6 10 14

11.14  What will be displayed by the following program?

def m(list):
    v = list[0]
    for e in list:
      if v < e: v = e
    return v

values = [[3, 4, 5, 1], [33, 6, 1, 2]]

for row in values: 
    print(m(row), end = " ")
A. 3 33
B. 1 1
C. 5 6
D. 5 33
E. 33 5

11.15  What will be displayed by the following code?

data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

print(data[1][0][0])
A. 1
B. 2
C. 4
D. 5
E. 6

11.16  What will be displayed the following code?

data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

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

11.17  What will be displayed by the following code?

points = [[1, 2], [3, 1.5], [0.5, 0.5]]
points.sort()
print(points)
A. [[1, 2], [3, 1.5], [0.5, 0.5]]
B. [[3, 1.5], [1, 2], [0.5, 0.5]]
C. [[0.5, 0.5], [1, 2], [3, 1.5]]
D. [[0.5, 0.5], [3, 1.5], [1, 2]]

Section 12.2 Superclasses and Subclasses


12.1  Analyze the following code:

class A:
    def __init__(self, i = 0):
        self.i = i

class B(A):
    def __init__(self, j = 0):
        self.j = j

def main():
    b = B()
    print(b.i)
    print(b.j)

main()
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.

12.2  What will be displayed by the following code?

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

12.3  What is the output of the following code?

 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)

Section 12.3 Overriding Methods


12.6  What will be displayed by the following code?

class A:
    def __init__(self, i = 0):
        self.i = i

    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

12.7  Which of the following statements is true?


A. A subclass is a subset of a superclass.
B. When invoking a constructor from a subclass, its superclass's no-arg constructor is
always invoked.
C. You can override a non-private method defined in a superclass.
D. You can override the initializer defined in a superclass.
E. You can override a private method defined in a superclass.

Section 12.4 The object Class


12.8  What will be displayed by the following code?

class A:
    def __new__(self):
        self.__init__(self)
        print("A's __new__() invoked")

    def __init__(self):
        print("A's __init__() invoked")

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

12.9  Which of the following statements is true?


A. By default, the __new__() method invokes the __init__ method.
B. The __new__() method is defined in the object class.
C. The __init__() method is defined in the object class.
D. The __str__() method is defined in the object class.
E. The __eq__(other) method is defined in the object class.

Section 12.5 Polymorphism and Dynamic Binding


12.10  What will be displayed by the following code?

class A:
    def __init__(self):
        self.i = 1

    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.

12.11  What will be displayed by the following code?

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

12.12  What will be displayed by the following code?

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

12.14  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
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

12.16  Analyze the following code:

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__()
        
    def setI(self, i):
        self.i = 3 * i;

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".

12.17  Analyze the following code:

class A:
    def __init__(self):
        self.setI(20)

    def setI(self, i):


        self.i = 2 * i;

class B(A):
    def __init__(self):
        super().__init__()
        print("i from B is", self.i)
        
    def setI(self, i):
        self.i = 3 * i;

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".

Section 12.6 The isinstance Function


12.18  To check whether an object o is an instance of class A, use _________.
A. o.isinstance(A)
B. A.isinstance(o)
C. isinstance(o, A)
D. isinstance(A, o)

Section 12.8 Class Relationships


12.19  What relationship is appropriate for Company and Employee?
A. association
B. composition
C. inheritance

12.20  What relationship is appropriate for Course and Faculty?


A. association
B. composition
C. inheritance
12.21  What relationship is appropriate for Student and Person?
A. association
B. composition
C. inheritance

12.22  What relationship is appropriate for House and Window?


A. association
B. composition
C. inheritance

12.23  What relationship is appropriate for Account and Savings Account?


A. association
B. composition
C. inheritance

Chapter 13 Files and Exceptions Handling

Section 13.2 Text Input and Output


13.1  To open a file c:\scores.txt for reading, use __________.
A. infile = open("c:\scores.txt", "r")
B. infile = open("c:\\scores.txt", "r")
C. infile = open(file = "c:\scores.txt", "r")
D. infile = open(file = "c:\\scores.txt", "r")

13.2  To open a file c:\scores.txt for writing, use __________.


A. outfile = open("c:\scores.txt", "w")
B. outfile = open("c:\\scores.txt", "w")
C. outfile = open(file = "c:\scores.txt", "w")
D. outfile = open(file = "c:\\scores.txt", "w")

13.3  To open a file c:\scores.txt for appending data, use ________


A. outfile = open("c:\\scores.txt", "a")
B. outfile = open("c:\\scores.txt", "rw")
C. outfile = open(file = "c:\scores.txt", "w")
D. outfile = open(file = "c:\\scores.txt", "w")
13.4  Which of the following statements are true?
A. When you open a file for reading, if the file does not exist, an error occurs.
B. When you open a file for writing, if the file does not exist, an error occurs.
C. When you open a file for reading, if the file does not exist, the program will open an
empty file.
D. When you open a file for writing, if the file does not exist, a new file is created.
E. When you open a file for writing, if the file exists, the existing file is overwritten with
the new file.

13.5  To read two characters from a file object infile, use _________.
A. infile.read(2)
B. infile.read()
C. infile.readline()
D. infile.readlines()

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.9  The readlines() method returns a ____________.


A. str
B. a list of lines
C. a list of single characters
D. a list of integers

13.10  The ______ function can be used to check if a file f exists.


A. os.path.isFile(f)
B. os.path.exists(f)
C. os.path.isfile(f)
D. os.isFile(f)

Section 13.3 File Dialogs


13.11  _____________ displays a file dialog for opening an existing file.
A. filename = askopenfilename()
B. filename = asksaveasfilename()
C. filename = openfilename()
D. filename = saveasfilename()

13.12  _____________ displays a file dialog for saving a file.


A. filename = askopenfilename()
B. filename = asksaveasfilename()
C. filename = openfilename()
D. filename = saveasfilename()

Section 13.5 Retrieving Data from the Web


13.13  _____________ opens a URL for input.
A. infile = urllib.request.urlopen(urlString)
B. infile = urllib.urlopen(urlString)
C. infile = request.urlopen(urlString)
D. infile = urlopen(urlString)

13.14  Invoking the ___________ method converts raw byte data to a string.
A. encode()
B. decode()
C. convert()
D. toString()

Section 13.6 Exception Handling


13.15  What is displayed when the following program is run?

try:
    list = 5 * [0]
    x = list[5]
    print("Done")
except IndexError: 
    print("Index out of bound")
A. "Done" followed by "Index out of bound"
B. "Index out of bound"
C. "Done"
D. Nothing displayed

13.16  What is displayed when the following program is run?

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"

13.17  What is displayed when the following program is run?

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"

13.18  What is displayed when the following program is run?

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"

Section 13.10 Binary IO Using Picking


13.19  To open a file c:\scores.dat for binary writing, use __________.
A. outfile = open("c:\\scores.dat", "wb")
B. outfile = open("c:\\scores.dat", "w")
C. outfile = open("c:\scores.dat", "a")
D. outfile = open("c:\\scores.dat", "w")

13.20  To open a file c:\scores.dat for binary reading, use __________.


A. infile = open("c:\\scores.dat", "rb")
B. infile = open("c:\\scores.dat", "r")
C. infile = open("c:\scores.dat", "wrb")
D. infile = open("c:\\scores.dat", "r")

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

Chapter 14 Tuples, Sets, and Dictionaries

Section 14.2 Tuples


14.1  Suppose t = (1, 2, 4, 3), which of the following is incorrect?
A. print(t[3])
B. t[3] = 45
C. print(max(t))
D. print(len(t))
E. print(sum(t))

14.2  Suppose t = (1, 2, 4, 3), t[1 : 3] is _________.


A. (1, 2)
B. (1, 2, 4)
C. (2, 4)
D. (2, 4, 3)
E. (1, 2, 4, 3)

14.3  Suppose t = (1, 2, 4, 3), t[1 : -1] is _________.


A. (1, 2)
B. (1, 2, 4)
C. (2, 4)
D. (2, 4, 3)
E. (1, 2, 4, 3)

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

14.6  Suppose t1 = (1, 2, 4, 3) and t2 = (1, 2, 3, 4), t1 < t2 is ________.


A. True
B. False

Section 14.3 Sets


14.7  Which of the following statements produces {'a', 'b', 'c'}?
A. list("abac")
B. tuple("abac")
C. set("abac")
D. None

14.8  You can use ___________ to create an empty set.


A. { }
B. ( )
C. [ ]
D. set()

14.9  Given two sets s1 and s2, s1 < s2 is _________.


A. true if len(s1) is less than len(s2)
B. true ifthe elements in s1 are compared less than the elements in s2.
C. true if s1 is a proper subset of s2
D. true if s1 is a proper superset of s2
E. illegal

14.10  Suppose s = {1, 2, 4, 3}, _______ returns 4.


A. sum(s)
B. len(s)
C. min(s)
D. max(s)
E. None
14.11  Suppose s = {1, 2, 4, 3}, which of the following is incorrect?
A. print(s[3])
B. s[3] = 45
C. print(max(s))
D. print(len(s))
E. print(sum(s))

14.12  Suppose s = {1, 2, 4, 3}, what happens when invoking s.add(4)?


A. There is no add method for a set object.
B. This method is executed fine and 4 is added to the set.
C. Since 4 is already in the set, Python raises a KeyError exception.
D. You cannot add an element from a set.
E. This method is executed fine and 4 is not added to the set since 4 is already in the set.

14.13  Suppose s = {1, 2, 4, 3}, what happens when invoking s.remove(12)?


A. There is no remove method for a set object.
B. This method is executed fine and no exception is raised.
C. Since 12 is not in the set, Python raises a KeyError exception.
D. You cannot remove an element from a set.

14.14  Suppose s1 = {1, 2, 4, 3} and s2 = {1, 3, 4, 2}, ________ is true.


A. s1 == s2
B. s1 != s2

14.15  Suppose s1 = {1, 2, 4, 3} and s2 = {0, 1, 5, 3, 4, 2, 13}, ________ is true.


A. s1.issubset(s2)
B. s1.issuperset(s2)
C. s2.issubset(s1)
D. s2.issuperset(s1)

14.16  Suppose s1 = {1, 2, 4, 3} and s2 = {1, 5, 4, 13}, what is s1 | s2?


A. {1, 2, 4, 3, 1, 5, 4, 13}
B. {1, 2, 4, 3, 5, 13}
C. {1, 2, 4, 3}
D. {1, 5, 4, 13}

14.17  Suppose s1 = {1, 2, 4, 3} and s2 = {1, 5, 4, 13}, what is s1 - s2?


A. {2, 3, 5, 13}
B. {1, 2, 4, 3, 5, 13}
C. {1, 2, 4, 3}
D. {1, 5, 4, 13}
E. {2, 3}

14.18  Suppose s1 = {1, 2, 4, 3} and s2 = {1, 5, 4, 13}, what is s1 & s2?


A. {2, 3, 5, 13}
B. {1, 2, 4, 3, 5, 13}
C. {1, 4}
D. {1, 5, 4, 13}
E. {2, 3}

14.19  Suppose s1 = {1, 2, 4, 3} and s2 = {1, 5, 4, 13}, what is s1 ^ s2?


A. {2, 3, 5, 13}
B. {4, 3, 5, 13}
C. {1, 4}
D. {1, 5, 4, 13}
E. {2, 3}

14.20  Which of the following statement is false?


A. Lists are mutable
B. Tuples are mutable
C. Sets are mutable
D. Strings are mutable

14.21  You can have duplicate elements in a ________?


A. list
B. tuple
C. set

14.22  The elements in a ________ are ordered?


A. list
B. tuple
C. set

14.23  Suppose s = {1, 2}, 2 * s is _________.


A. (1, 2, 1, 2)
B. [1, 2, 1, 2]
C. (1, 1, 2, 2)
D. [1, 1, 2, 2]
E. illegal

14.24  Suppose s1 = {1, 2, 4, 3} and s2 = {1, 5, 4, 13}, s1 + s2 is ____________?


A. {1, 2, 4, 3, 1, 5, 4, 13}
B. {1, 2, 4, 3, 5, 13}
C. {1, 2, 4, 3}
D. {1, 5, 4, 13}
E. illegal

Section 14.5 Dictionary


14.25  Which of the following statements create a dictionary?
A. d = {}
B. d = {"john":40, "peter":45}
C. d = {40:"john", 45:"peter"}
D. d = (40:"john", 45:"peter")

14.26  Suppose d = {"john":40, "peter":45}, the keys are __________


A. "john", 40, 45, and "peter"
B. "john" and "peter"
C. 40 and 45
D. d = (40:"john", 45:"peter")

14.27  Suppose d = {"john":40, "peter":45}, "john" in d is __________


A. True
B. False

14.28  Suppose d1 = {"john":40, "peter":45} and d2 = {"john":466, "peter":45}, d1 == d2 is


_______.
A. True
B. False
C. illegal

14.29  Suppose d1 = {"john":40, "peter":45} and d2 = {"john":466, "peter":45}, d1 > d2 is


_______.
A. True
B. False
C. illegal

14.30  Suppose d = {"john":40, "peter":45}, d["john"] is __________


A. 40
B. 45
C. "john"
D. "peter"

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()

14.33  What will be displayed by the following code?

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.

14.37  Which of the following is a Python list?


A. [1, 2, 3]
B. (1, 2, 3)
C. {1, 2, 3}
D. {}

14.38  Which of the following is a Python tuple?


A. [1, 2, 3]
B. (1, 2, 3)
C. {1, 2, 3}
D. {}

14.39  Which of the following is a Python set?


A. [1, 2, 3]
B. (1, 2, 3)
C. {1, 2, 3}
D. {}

14.40  Which of the following is a Python dictionary?


A. [1, 2, 3]
B. (1, 2, 3)
C. {1, 2, 3}
D. {}

14.41  Which of the following sets is equal to {1, 2, 3}?


A. {1, 2, 3}
B. {2, 1, 3}
C. {3, 2, 1}
D. {2, 3, 1}
E. {1, 2, 3, 2, 1, 3}

Chapter 15 Recursion

Section 15.2 Problem: Computing Factorials


15.1  Which of the following statements are true?
A. Every recursive function must have a base case or a stopping condition.
B. Every recursive call reduces the original problem, bringing it increasingly closer to a
base case until it becomes that case.
C. Infinite recursion can occur if recursion does not reduce the problem in a manner that
allows it to eventually converge into the base case.
D. Every recursive function must have a return value.
E. A recursive function is invoked differently from a non-recursive function.

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

15.4  Analyze the following recursive function.

  def factorial(n):
      return n * factorial(n - 1)
  
A. Invoking factorial(0) returns 0.
B. Invoking factorial(1) returns 1.
C. Invoking factorial(2) returns 2.
D. Invoking factorial(3) returns 6.
E. The function runs infinitely and causes a StackOverflowError.

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

Section 15.3 Problem: Computing Fibonacci Numbers


15.6  Which of the following statements are true?
A. The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of
the preceding two numbers in the series.
B. The Fibonacci series begins with 1 and 1, and each subsequent number is the sum of
the preceding two numbers in the series.
C. The Fibonacci series begins with 1 and 2, and each subsequent number is the sum of
the preceding two numbers in the series.
D. The Fibonacci series begins with 2 and 3, and each subsequent number is the sum of
the preceding two numbers in the series.

15.7  How many times is the fib function in Listing 15.2 invoked for fib(5)?
A. 14
B. 15
C. 25
D. 31
E. 32

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:

def xfunction(x, length):
    print(x[length - 1], end = " ")
    xfunction(x, length - 1)

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.

Section 15.5 Recursive Helper functions


15.13  Fill in the code to complete the following function for checking whether a string is a
palindrome.

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

        # Sort the remaining list(low+1 .. high)


        sortHelper(lst, low + 1, high)
A. sortHelper(lst)
B. sortHelper(lst, len(lst) - 1)
C. sortHelper(lst, 0, len(lst) - 1)
D. sortHelper(lst, 0, len(lst) - 2)

15.15  Fill in the code to complete the following function for binary search.

def recursiveBinarySearch(lst, key):
    low = 0
    high = len(lst) - 1
    return ________________________________________

def recursiveBinarySearchHelper(lst, key, low, high):
    if low > high: # The list has been exhausted without a match
        return ?low - 1

    mid = (low + high) // 2


    if key < lst[mid]:
        return recursiveBinarySearchHelper(lst, key, low, mid - 1)
    elif key == lst[mid]:
        return mid
    else:
        return recursiveBinarySearchHelper(lst, key, mid + 1, high)
A. recursiveBinarySearchHelper(lst, key)
B. recursiveBinarySearchHelper(lst, key, low + 1, high - 1)
C. recursiveBinarySearchHelper(lst, key, low - 1, high + 1)
D. recursiveBinarySearchHelper(lst, key, low, high)
15.16  What will displayed by the following code?

def main():
    times = count("abcabc", 'a')
    print(ch + " appears " + str(times) + (" times " if times > 1 else " time ") + "in " + s)
    
def count(s, a):
    return countHelper(s, a, len(s) - 1)

def countHelper(s, a, high):
    result = 0;
    if high > 0:
        result = countHelper(s, a, high - 1) + (1 if s[high] == a else 0)

    return result;

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

Section 15.7 Tower of Hanoi


15.17  How many times is the recursive moveDisks function invoked for 3 disks?
A. 3
B. 7
C. 10
D. 14

15.18  How many times is the recursive moveDisks function invoked for 4 disks?
A. 5
B. 10
C. 15
D. 20

15.19  Analyze the following two programs:

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.

Section 15.10 Recursion versus Iteration


15.20  Which of the following statements are true?
A. Recursive functions run faster than non-recursive functions.
B. Recursive functions usually take more memory space than non-recursive functions.
C. A recursive function can always be replaced by a non-recursive function.
D. In some cases, however, using recursion enables you to give a natural,
straightforward, simple solution to a program that would otherwise be difficult to solve.

Section 15.11 Tail Recursion


15.21  Analyze the following functions;

def f1(n):
    if n == 0:
        return 0
    else:
        return n + f1(n - 1)

def f2(n, result):
    if n == 0:
        return result
    else:
        return f2(n - 1, n + result)

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

15.22  Show the output of the following code:

def f2(n, result):
    if n == 0:
        return 0
    else:
        return f2(n - 1, n + result)

print(f2(2, 0))
A. 0
B. 1
C. 2
D. 3

Chapter 16 Developing Efficient Algorithms

Section 16.2 Measuring Algorithm Efficiency Using Big O Notation


16.1  Estimating algorithm efficiency is ________
A. to measure their actual execution time.
B. to estimate their execution time.
C. to estimate their growth function.

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.5  On an average, linear search searches


A. the whole list
B. half of the list
C. just one element in the list
D. one fourth of the list

Section 16.3 Examples: Determining Big O


16.6  What is the number of iterations in the following loop:

 int count = 5;
 while (count < n) {
   count = count + 3;
 }
A. n - 5
B. n - 3
C. n / 3 - 1
D. (n - 5) / 3
E. the ceiling of (n - 5) / 3

Section 16.4 Analyzing Algorithm Time Complexity


16.7  For a sorted list of 1024 elements, a binary search takes at most _______ comparisons.
Note that to check whether an element is greater than, equal to, or less than the other element
is considered as one comparison here.
A. 11
B. 100
C. 512
D. 6

16.8  O(1) is ________.


A. constant time
B. logarithmic time
C. linear time
D. log-linear time

16.9  The time complexity for the Towers of Honoi algorithm in the text is ________.
A. O(n)
B. O(n^2)
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)

Section 16.5 Finding Fibonacci Numbers Using Dynamic Programming


16.12  ______________ approach is the process of solving subproblems, then combining the
solutions of the subproblems to obtain an overall solution. This naturally leads to a recursive
solution. However, it would be inefficient to use recursion, because the subproblems overlap.
The key idea behind dynamic programming is to solve each subproblem only once and store
the results for subproblems for later use to avoid redundant computing of the subproblems.
A. Divide-and-conqure
B. Dynamic programming
C. Brutal-force
D. Backtracking

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)

Section 16.8 Finding the Closest Pair of Points Using Divide-and-Conquer


16.17  The time complexity for the the closest pair of points problem using divide-and-
conquer is ________.
A. O(n)
B. O(nlogn)
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

Section 16.9 Solving the Eight Queens Problem Using Backtracking


16.19  The ________ approach searches for a candidate solution incrementally, abandoning
that option as soon as it determines that the candidate cannot possibly be a valid solution, and
then looks for a new candidate.
A. Divide-and-conqure
B. Dynamic programming
C. Brutal-force
D. Backtracking
Section 16.10 Computational Geometry: Finding a Convex Hull
16.20  The gift-wrapping algorithm for finding a convex hull takes ______________ time.
A. O(n)
B. O(nlogn)
C. O(logn)
D. O(n^2)

16.21  The Graham's algorithm for finding a convex hull takes ______________ time.
A. O(n)
B. O(nlogn)
C. O(logn)
D. O(n^2)

Вам также может понравиться