Table of Contents
CS105: Introduction to Python Exam Quiz Answers
Question 1: What will happen when these two commands are executed in the command line window?
> a=4
> type(a)
- The number 4 will be echoed to the screen
- The character a will be echoed to the screen
- <class ‘int’> will be echoed to the screen
- An error will occur because type is not a valid command
Question 2: What is the data type of the variable a after this assignment takes place?
> z=5e03
- z is of type str because it contains the character ‘e’
- a is of type bool because it contains characters and numbers
- a is of type int because the 5 is not followed by a decimal point
- z is of type float because it is expressed using scientific notation
Question 3: What will be echoed to the screen when these commands are executed in the command line window?
> b=4
> c=3
> c=b
> c=1
> c
- The number 1
- The number 3
- The number 4
- The character ‘c’
Question 4: What will be printed to the screen when these commands are executed in the command line window?
> a=20
> c=a*5
> print (‘value 1 = ‘, a,‘, value 2 = ‘, c)
- ‘Value 1 = 20, value 2 = 20’
- ‘Value 1 = 20, value 2 = 100’
- ‘Value 1 = 100, value 2 = 20’
- ‘Value 1 = 100, value 2 = 100’
Question 5: What value will be echoed to the screen when these commands are executed in the command line window?
> str (float (32))
- 32
- 32.0
- ’32’
- ‘32.0’
Question 6: Assume you have just executed these commands:
a=3
b=5
c=a**b
Which of the following is equivalent to the expression for c?
- a*b
- b*b*b
- a*b*a*b
- a*a*a*a*a
Question 7: When using expressions that contain a mixture of relational operators and logical operators, which of the following is true?
- The logical operators are disregarded
- The relational operators are disregarded
- Logical operators have higher precedence than relational operators
- Relational operators have higher precedence than logical operators
Question 8: Which of the following statements about programmer-initialized variables is true?
- They can be initialized without user input
- They must be initialized as a string data type
- They must be initialized as a numerical data type
- They cannot be changed after they have been assigned
Question 9: Assume this instruction executes in the Repl.it run window.
print(input(‘Input a letter: ‘)>input(‘Input a letter: ‘))
What will be the result of this instruction?
- A Boolean True will be generated
- A Boolean False will be generated
- An error will occur because this syntax is invalid
- The alphabetical order of the two input characters will be compared
Question 10: Which of the following can the ‘continue’ instruction be useful for?
- Stopping a program from terminating
- Disregarding a variable assignment within a loop
- Allowing a program to continue when an input error occurs
- Skipping over a set of commands within a loop and beginning the next iteration
Question 11: An important property of lists is that they have which of the following characteristics?
- They are static
- They are global
- They are mutable
- They are immutable
Question 12: Which of the following sets of instructions will generate the exact same output as this code?
c=[2,4,6,8,1,3,5,7]
for i in range(len(c)):
print(c[i])
- print(c)
- for val in c:
print(val)
- for i in range(7):
print(c[i])
- for i in range(9):
print(c[i])
Question 13: Given the list:
a=[-1,-2,-3,-4,5,6,7,8]
what output would the instruction:
a[::-1]
generate?
- -1
- 8
- [8, 7, 6, 5, -4, -3, -2, -1]
- An error, because a negative index has been used
Question 14: Assume within a program, a set of instructions to accomplish a specific task is reused several times. Which of the following could the task be housed within to improve the program?
- A built-in function
- A recyclable function
- A procedural function
- A user-defined function
Question 15: Which punctuation mark must the definition line for a function must end with?
- Colon
- Comma
- Period
- Semicolon
Question 16: What will the output be after this code runs?
def listsum(alist,sval):
s=0
for val in alist:
if val>sval:
s+=val
return s
x=[-4,-34,6,0,1,4,2]
t=1
z=listsum(x,t)
print(z)
- 0
- 1
- 7
- 12
Question 17: Assume import math has been invoked and that n is a variable of type int.
def coslist(n):
x=[ ]
c=[ ]
d=2*math.pi/n
for u in range(n+1):
x.append(d*u)
c.append(math.cos(x[u]))
return x,c
What is this function computing?
- The cosine function over the interval 0 to pi
- The cosine function over the interval 0 to 2*pi
- The cosine function over the interval n to pi
- The cosine function over the interval n to 2*pi
Question 18: Why would this set of instructions not be allowed in Python?
atuple=(4,5,6,7,8)
atuple[4]=22
- Because tuples are not mutable
- Because an index cannot be used to access tuple elements
- Because tuple elements must be separated by a semi-colon
- Because tuple elements must be contained within curly brackets, not parentheses
Question 19: Which of the following statements is true?
- Sets are an ordered collection of elements and are mutable
- Sets are an unordered collection of elements and are mutable
- Sets are an ordered collection of elements and are not mutable
- Sets are an unordered collection of elements and are not mutable
Question 20: After these instructions execute, what values will the variable z contain?
xdict=dict([(‘k1’,‘v1’), (‘k2’,‘v2’),(‘k3’,‘v3’)])
z=set(xdict)
- {‘k1’, ‘k2’, ‘k3’}
- {‘v1’, ‘v2’, ‘v3’}
- {‘k1′,’v1’, ‘k2’, v2’, ‘k3′,’v3’}
- {‘k1’: ‘v1’, ‘k2’: ‘v2’, ‘k3’: ‘v3’}
Question 21: When using the open instruction, which of the following modes is assumed as the default if a file handling mode is not provided?
- a
- r
- r+
- w
Question 22: After executing the command
f = open(‘example.txt’,‘w’)
which of the following instructions will write the values 1, 2, and 3 as text data to a file?
- f.write([1,2,3])
- f.write(‘1 2 3’)
- f.write(‘1′,’2′,’3’)
- f.write([‘1′,’2′,’3’])
Question 23: Assume that the file source.txt contains the data:
2 4
3 5
4 6
Which of the following instructions will generate the output
8
15
24
?
- myfile = open(‘source.txt’)
for line in myfile:
line = line.rstrip()
a=line.split(‘ ‘)
print(a[0]*a[1])
myfile.close()
- myfile = open(‘source.txt’)
for line in myfile:
line = line.rstrip()
a=float(line.split(‘ ‘))
print(a[0]*a[1])
myfile.close()
- myfile = open(‘source.txt’)
for line in myfile:
line = line.rstrip()
a=line.split(‘ ‘)
print(int(a[0])*int(a[1]))
myfile.close()
- myfile = open(‘source.txt’)
for line in myfile:
line = line.rstrip()
a=int(line.split(‘ ‘))
print(a[0]*a[1])
myfile.close()
Question 24: Which of the following lines, when inserted into this code:
import re
def findstr(str_list):
#insert code here
regex = re.compile(pattern)
for val in str_list:
if regex.match(val):
print(val)
return
would match the strings:
‘. abcd’
‘ABCD. ‘
?
- pattern = ‘[A-Z]\.\s[a-z]*’
- pattern = ‘[A-Z]*\.\s[a-z]’
- pattern = ‘[A-Z]*\.\s[a-z]*’
- pattern = ‘[A-Z]+\.\s[a-z]+’
Question 25: Object-oriented programming uses methods for defining and accomplishing tasks. Which of the following does procedural programming use?
- Dictionaries
- Functions
- Snippets
- Variables
Question 26: Which of the following statements is true?
- A class is instance of an object
- An object is an instance of class
- A class cannot contain an object
- The term ‘object’ is another name for a class
Question 27: Given this class definition for a sphere:
class Sphere:
def __init__(self, r):
self.radius=r
Which of the following method definitions would enable you to execute the commands:
c1=Sphere(2)
c2=Sphere(3)
print(c1>=c2)
?
- def __ge__(self,other):
return self.radius>other.radius
- def __geq__(self,other):
return self.radius>other.radius
- def ge(self,other):
return self.radius>other.radius
- def geq(self,other):
return self.radius>other.radius
Question 28: Complete the function listprod so that it will compute the product of the elements contained in an input numerical list.
For example:
x=[1,1,1,2]
print(listprod(x))
would result in a value of 2, and
x=[2,1,1,-2]
print(listprod(x))
would result in a value of -4.
Answer:(penalty regime: 0 %)
def listprod(input_list):
result = 1 # Initialize the result to 1
for num in input_list:
result *= num # Multiply each element with the result
return result
Question 29: Complete the function listchk that takes a numerical list alist and a number n as the input. Starting with index 0, the function checks every other value in alist (that is, only the elements with even indices) to see if it is less than the input value n. A new list is returned that consists of all values contained in alist with even indices that are less than the input value n.
Answer:(penalty regime: 0 %)
def listchk(alist, n):
Question 30: Given the class definition Dictops, complete the method named keyvalsearch that, given an input key, will search the object attribute xdict for the associated value.
- A KeyError exception handler should return a value of float(‘Nan’).
- Otherwise, the function should return the value associated withe the input key.
Answer:(penalty regime: 0 %)
class Dictops:
def __init__(self, xdict):
self.xdict = xdict
def keyvalsearch(self, key):
try:
value = self.xdict[key]
except KeyError:
value = float(‘nan’)
return value
Question 31: When is a number in Python of type int?
- When it is written in scientific notation with a decimal point
- When it is written in scientific notation without a decimal point
- When it contains a decimal point with no digits following the decimal point
- When it does not contain a decimal point and it is not written in scientific notation
Question 32: Which of the following commands will reassign the variable b by adding the number 5 to b?
- 5=b+b
- b=b+5
- b=b*5
- b+5=b
Question 33: What will be printed to the screen when these commands are executed in the command line window?
> d=‘7’
> c=5
> print(d*c)
- 35
- 75
- ‘d*c’
- 77777
Question 34: What will be printed to the screen when these commands are executed in the command line window?
> s=‘abcdefghij’
> t=‘vwyz’
> print(t+s[0])
- 213
- ‘vwyza’
- ‘t+s[0]’
- ‘vawayaza’
Question 35: Assume you have just executed these commands:
a=47
b=5
c=a//b
d=a % b
Which of the following would compute the value contained in the variable a?
- b*b+d
- c*b+d
- c*c+d
- d*b+c
Question 36: What will the output be after this set of instructions executes?
i=0
while i>0:
print(i)
i=i+1
- No output, because the while loop does not execute
- An error, because the variable i is not greater than 0
- The while loop will print out integers starting at 0 in an infinite loop
- The while loop will print out integers starting at 1 in an infinite loop
Question 37: Which of the following can the ‘break’ instruction be useful for?
- Halting the execution of a program
- Changing a for loop into a while loop
- Exiting a loop abruptly when a certain condition is met
- Stopping the execution of the input instruction when invalid input is entered
Question 38: Why would the instruction c=zlist[6] be problematic, given this list?
zlist=[‘abc’,‘def’,3,4,5,‘ghi’]
- The character ‘c’ appears within the list
- The 6th element is ‘ghi’, which is a string
- The maximum index allowed for this list is 5
- The list mixes both numerical and string data
Question 39: Which index can be used to refer to the last element on a list?
- -2
- -1
- 0
- 0.0
Question 40: How might this code snippet be improved?
a= [2,3,4,5,6]
for i in range (5):
print(a[i])
a= [5,4,3,2]
for i in range (4):
print(a[i])
- By changing the variable names
- By using while loops instead of for loops
- By using range(len(a)) instead of range (5)
- By printing out the elements without using a loop
Question 41: Which of the following will enable the output of data from a function?
- Parentheses
- An equals sign
- A return statements
- A relational operator
Question 42: Which of the following lines could be inserted into this code snippet to create a function that adds two numerical lists (having the same length) element-by-element?
def add2lists(a,b):
c=[ ]
for i in range(len(a)):
#fill in intruction here
return c
x=[1,2,3,4]
y=[5,6,7,8]
z=add2lists(x,y)
- c=a+b
- c[i]=a[i]+b[i]
- return a[i]+b[i]
- c.append(a[i]+b[i])
Question 43: Which of the following methods is the arithmetic operator ** most similar to?
- math.exp
- math.log
- math.pow
- math.log2
Question 44: After executing this code snippet, which of the following is true about the variable s?
import random
s=0
for i in range(100):
s+=random.random()
- s must be less than 0
- s must be greater than 100
- s cannot exceed a value of 1
- s cannot exceed a value of 100
Question 45: The tuple is a sequence data type. Which punctuation marks are its elements separated, and which are they contained within?
- They are separated by commas and contained within parentheses
- They are separated by commas and contained within curly brackets
- They are separated by semicolons and contained within parentheses
- They are separated by commas and contained within square brackets
Question 46: If this set of instructions executes, which of the following will the output be most similar to?
asset={2,4,6,8,2,5,6}
print(asset)
- {2, 5, 6}
- {2, 4, 6, 8}
- {2, 4, 5, 6, 8}
- {2, 4, 6, 8, 2, 5, 6}
Question 47: What will the output be after this set of instructions executes?
xdict={1:‘v1’,2:[1,2,3,4],3:{4,5,6,7},4:‘sadfasdf’}
print(xdict[2][-1])
- 4
- 7
- ‘1’
- ‘f’
Question 48: What data will be contained in the file example.txt after executing this set of instructions?
f = open(‘example.txt’,‘w’)
f.write(‘a b c ‘)
f.write(‘d e f ‘)
f.close()
- a b c
- d e f
- a b c
d e f
- a b c d e f
Question 49: Consider this set of commands:
f = open(‘example.txt’,‘w’)
f.write(‘Hello \n’)
f.write(‘world ‘)
f.close()
f = open(‘example.txt’)
#instruction(s) to execute for this problem goes here …
f.close()
What instruction(s) must be inserted into this code in order to generate this screen output, formatted exactly as:
Hello
world
?
- print(f.read())
- print(f.read())
print(f.read())
- print(f.readline())
print(f.readline())
- print(f.readlines())
Question 50: Which of the following regular expressions can be used to search a list of names where the name(s) to be found follows the pattern ‘FirstName MiddleInitial. LastName’?
- ‘. [A-Z] \s’
- ‘.\s[A-Z]’
- ‘[A-Z] \.\s$’
- ‘[A-Z] \.\s’
Question 51: Which of the following, if used in a program, would be considered to be a deviation from structured programming?
- Functions
- ‘if’ statements
- ‘for’ statements
- ‘break’ statements
Question 52: Given a user-defined class Circle with the data attribute radius, which of the following methods would be appropriate for the object instantiation
c1=Circle (2)
?
- def init(self, r):
self.radius=r
- def __init__(self, r):
self.radius=r
- def __init__(r):
init.radius=r
- def init(r):
init.radius=r
Question 53: Complete the function distprop that will verify the following distributive property for sets:
A∪(B∩C)=(A∪B)∩(A∪C)�∪(�∩�)=(�∪�)∩(�∪�)
where:
- ∪∪ indicates the union operation
- ∩∩ indicates the intersection operation
Using this function definition line:
def distprop(A,B,C):
- First compute: A∪(B∩C)�∪(�∩�)
- Then compute: (A∪B)∩(A∪C)(�∪�)∩(�∪�)
If the two are equal, return True; otherwise, return False.
Answer:(penalty regime: 0 %)
def distprop(A, B, C):
# Compute A ∪ (B ∩ C)
left_side = A.union(B.intersection(C))
# Compute (A ∪ B) ∩ (A ∪ C)
right_side = (A.union(B)).intersection(A.union(C))
# Check if the two sets are equal
if left_side == right_side:
return True
else:
return False
Question 54: What number will be echoed to the screen when this command is executed in the command line window?
> float(int(float(0.0034e3))
- 34
- 3.0
- 3.4
- 34.0
Question 55: What will be printed to the screen when these commands are executed in the command line window?
> a=25
> b=30
> a=5*a
> b=b-10
> print(‘value 1 =’,a,‘, value 2 =’,b)
- ‘Value 1 = 25, value 2 = 30’
- ‘Value 1 = 125, value 2 = 20’
- ‘Value 1 = 140, value 2 = 150’
- ‘Value 1 = 150, value 2 = 140’
Question 56: Given two variables x and y of type int, which of the following is a valid expression that is equivalent to x! =y?
- x == not y
- x>y or x<y
- x not == y
- x>y and x<y
Question 57: What is the output of this code snippet if it is executed using the Repl.it run window?
a=False
b=True
c=True
y= a or b and c
print(y)
- 0
- 1
- True
- False
Question 58: Assume this set of instructions is executed in the Repl.it run window.
a=5
z=input(‘Enter your first name: ‘)
print(a)
print(z)
Which of the following would the variable z be considered?
- An empty string
- A user input variable
- A variable of type
int
- A programmer-initialized variable
Question 59: What will the output be after this set of instructions executes?
x=2
y=3
z=4
if (x<=2) and (y>3):
print(‘1’)
elif (x<=2) and (y==3):
print(‘2’)
elif (x==2) and (y>=3):
print(‘3’)
else:
print(‘4’)
- 1
- 2
- 3
- 4
Question 60: What will this code snippet output?
a=[0,1,2,3,4,5,6,7,8,9]
s=0
for z in a:
if z%2==0:
s+=z
print(s)
- 0
- 1
- 20
- 25
Question 61: Given the list:
a= [1,2,3,4,5,6,7,8,9,10]
which of the following instructions could be used to create the list:
[1, 2, 3, 4]?
- a [0:3]
- a [0:4]
- a [1:4]
- a [1:5]
Question 62: How might this code snippet be improved?
a=[-2,4,-12,5,6,7,8,9]
s=0
for z in a:
s+=z
- By replacing the for loop with print(a)
- By replacing the for loop with s=len(a)
- By replacing the for loop with s=max(a)
- By replacing the for loop with s=sum(a)
Question 63: Assuming import math has been invoked, which of the following outputs will the instruction
print(math.pow(2,math.log10(1000)))
yield?
- 2.0
- 3.0
- 8.0
- 10.0
Question 64: Assuming import random has been invoked, what is the smallest possible value the variable x could be for this instruction?
x=random.random()
- -1e300
- -1.0
- 0.0
- 1.0
Question 65: What will the output be after this set of instructions executes?
xdict=dict([(1,’v1′), (2,’v2′),(3,’v3′)])
ydict=dict([(‘v1’,1), (‘v2’,2),(‘v3’,3)])
ydict.update(xdict)
ydict[‘v2’]=23
print(ydict)
- {‘v1’: 1, ‘v2’: 23, ‘v3’: 3}
- {‘v1’: 1, ‘v2’: 2, ‘v3’: 3, 1: ‘v1’, 2: 23, 3: ‘v3’}
- {‘v1’: 1, ‘v2’: 23, ‘v3’: 3, 1: ‘v1’, 2: 23, 3: ‘v3’}
- {‘v1’: 1, ‘v2’: 23, ‘v3’: 3, 1: ‘v1’, 2: ‘v2’, 3: ‘v3’}
Question 66: What data will be contained in the file example.txt after executing this set of instructions?
f = open(‘example.txt’,‘w’)
f.write(‘1 2 3 ‘)
f.close()
f = open(‘example.txt’,‘w’)
f.write(‘4 5 6 ‘)
f.close()
- 1 2 3
- 4 5 6
- 1 2 3
4 5 6
- 1 2 3 4 5 6
Question 67: Given this code snippet:
f = open(‘example.txt’,‘w’)
f.write(‘5 \n 10 \n 15 \n 20 \n’)
f.write(‘world ‘)
f.close()
f = open(‘example.txt’)
#insert instruction(s) here
f.close()
print(b/a)
Which of the following instruction(s) will yield the screen output:
1.5
?
- [a,b]=f.read()
- f.readline()
a=float(f.readline())
b=float(f.readline())
- f.readline()
f.readline()
a=float(f.readline())
b=float(f.readline())
- a=float(f.readline())
b=float(f.readline())
Question 68: Where does the match method in the re module search for a match of a pattern?
- Anywhere within a list
- At the beginning of a list
- Anywhere within a string
- At the beginning of a string
Question 69: Given this function:
import re
def re_pattern(text, pattern):
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
print(text[s:e])
return
which of the following function calls would generate the output:
123
123
123
123
?
- re_pattern(‘d123d123d123d123’, ‘d*’)
- re_pattern(‘d123d123d123d123’, ‘\d’)
- re_pattern(‘d123d123d123d123’, ‘\d+’)
- re_pattern(‘d123d123d123d123’, ‘\D+’)
Question 70: If this set of instructions were to execute, what would be the most appropriate exception handler?
try:
x=float(input(‘Input a number:’))
- except NameError:
print(‘NameError’)
- except TypeError:
print(‘TypeError’)
- except ArithmeticError:
print(‘ArithmeticError’)
- except ValueError:
print(‘ValueError’)
Question 71: Given this class definition for a sphere:
class Sphere:
def __init__(self, r):
self.radius=r
Which of the following method definitions would enable you to execute the commands:
c1=Sphere(2)
c2=Sphere(3)
print(c1>=c2)
?
- def __ge__(self,other):
return self.radius>other.radius
- def __geq__(self,other):
return self.radius>other.radius
- def ge(self,other):
return self.radius>other.radius
- def geq(self,other):
return self.radius>other.radius
Question 72: Complete the method named charsearch in the class definition for Listops that will search the object attribute xlist (a list of strings) and return the number of strings that begin with the input character sval.
For example, if xlist contains:
[‘asdf’, ‘dfgh’, ‘sdfg’, ‘sfghj’, ‘swertq’, ‘qtyiu’]
and sval is ‘s’, then the method should return a value of 3.
Answer:(penalty regime: 0 %)
class Listops:
def __init__(self, xlist):
self.xlist = xlist
def charsearch(self, sval):
count = 0
for string in self.xlist:
if string.startswith(sval):
count += 1
return count
Question 73: What will happen when these two commands are executed in the command line window?
> a=4
> a
- The number 4 will be echoed to the screen
- The character a will be echoed to the screen
- The number 4.0 will be echoed to the screen
- An error will occur because the print(a) command was not used
Question 74: What will be echoed to the screen when these commands are executed in the command line window?
> b=3
> b=b+5
> b=b+b
> b
- The number 4
- The number 9
- The number 16
- The character ‘b’
Question 75: What should this expression result in an output of, and why?
print(2**3*2)
- 12, because 2, 3, and 2 are multiplied together
- 16, because exponentiation takes place before multiplication
- 64, because multiplication takes place before exponentiation
- An error, because ** is not a valid Python operation
Question 76: What is the output of this code snippet if it is executed using the Repl.it run window?
x=12
z=8
a=x/z<=x//z
print(a)
- 1
- 1.5
- True
- False
Question 77: Assume this set of instructions is executed in the Repl.it run window.
a=float(input(‘Input a number: ‘))
b=int(input(‘Input a number: ‘))
c=input(‘Input a number: ‘)
print(type(a+b+(c==1)))
What will be the resulting output?
- <class ‘int’>
- <class ‘bool’>
- <class ‘float’>
- An error, because == is comparing a str with an int
Question 78: Given this code snippet:
a=30
b=-20
c=0
if (a>30) and (b>-20) or (c==0):
print(‘The condition is True’)
else:
print(‘The condition is False’)
the output will be:
The condition is True
Which of the following changes to the if condition will cause the output to be:
The condition is False
?
- a<30
- b<-20
- c>0
- c>=0
Question 79: What will the output be after this set of instructions executes?
i=0
s=‘tomorrow’
while s[i]!=‘r’:
i+=1
print(i)
- 0
- 4
- 5
- 7
Question 80: Which of the following can be used to refer to specific values contained within a list?
- Container
- Index
- Operator
- Sequence
Question 81: Given the set of instructions
a= [1,2,3,4]
b= {1,2,3,4}
c= (1,2,3,4)
xdict= {‘k1’: a, ‘k2’: b, ‘k3’: c}
which of the following statements are true?
- xdict[‘k1’] refers to a set
- xdict[‘k1’] refers to a tuple
- xdict[‘k3’] refers to a set
- xdict[‘k3’] refers to a tuple
Question 82: Which of the following will happen after these instructions attempt to execute?
atuple=(‘a’,‘b’,5.7,9)
z=list(atuple)
- The variable z will be a list
- The variable z will be a tuple
- z=list(atuple) will cause an error because tuples are immutable
- atuple=(‘a’,’b’,5.7,9) will cause an error because the elements are not the same data type
Question 83: If the set of instructions
aset={‘q’,‘b’,1,4,9}
bset={5,7,8,‘g’}
cset=aset.union(bset)
executes, which of the following instructions would be equivalent to
cset=aset.union(bset)
?
- cset=bset==aset
- cset=bset!=aset
- cset=bset.union(aset)
- cset=bset.intersection(aset)
Question 84: Which of the following instructions will complete the ‘for’ statement in this code so that it prints out each line of the file source.txt?
myfile = open(‘source.txt’,‘r’)
for #complete this for statement
print(line)
myfile.close()
- for line:
- for line in myfile:
- for myfile in line:
- for line in range(myfile):
Question 85: Which of the following does inheritance gives you the ability to do?
- Define a new method within an existing class
- Instantiate multiple objects from an existing class
- Overload an existing method within an existing class
- Define a new class that is a modified version of an existing class
Question 86: What will be printed to the screen when these commands are executed in the command line window?
> y=’Chicago’
> z=’London’
> print (‘%s and %s are considered to be large cities’ % (z, y))
- ‘y and z are considered to be large cities’
- ‘z and y are considered to be large cities’
- ‘Chicago and London are considered to be large cities’
- ‘London and Chicago are considered to be large cities’
Question 87: Given this code snippet:
x=2
y=-5
z=1
if x>0 or y<3:
print (‘1’)
elif z>-1 or y<-1:
print (‘2’)
else:
print (‘3’)
the output will be:
1
Which of the following changes to the if-elif-else condition will cause the output to be:
2
?
- if x<0 or y<3:
- if x<0 or y>3:
- elif z==1 or y<-1:
- elif z>=1 or y>-1:
Question 88: If the value of c in this code snippet were to be changed:
a=-10
b=20
c=1
for k in range (a, b, c):
if k==10:
print(k)
which of the following choices would not cause the value of 10 to be output?
- c=2
- c=4
- c=8
- c=10
Question 89: Given this code snippet:
a= [2]
for i in range (5):
a.append(#fill in your expression here)
print(a)
which of the following definitions of the variable a will generate the output
[2, 2, 3, 5, 8, 12]
?
- a.append(i+i)
- a.append(a[i]+i)
- a.append(a[i]-i)
- a.append(a[i]+2*i)
Question 90: You want to plot the function y=2x. Why would this code be problematic?
import matplotlib. pyplot as plt
x= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
plt. plot(x,2*x)
- The operation 2*x is invalid
- plt is not an allowed object name
- matplotlib cannot be used to plot functions
- The list defined by x does not contain enough data
Question 91: Which of the following lines will complete the ‘if’ statement in the function listmax so that it will find the minimum value on a numerical list?
def listmin(alist):
m=alist [0]
for val in alist:
if #complete this if statement:
m=val
return m
x= [-4, -34,6,0,1,4,2]
z=listmin(x)
- if val<m:
- if val>m:
- if val==m:
- if val! =m:
Question 92: After executing this code snippet, which of the following is true about the variable z?
import random
c= [ ]
for i in range (100):
c.append (random. random ())
z=max(c)
- z must be less than 0.0
- z must be less than 1.0
- z must be greater than 1.0
- z must be greater than 100.0
Question 93: Which of the following is this instruction equivalent to?
xdict=dict([(‘k1′,’v1’), (‘k2′,’v2’), (‘k3′,’v3’)])
- xdict= {‘k1’: ‘v1’, ‘k2’: ‘v2’, ‘k3’: ‘v3’}
- xdict= {[‘k1’: ‘v1’, ‘k2’: ‘v2’, ‘k3’: ‘v3’]}
- xdict= {(‘k1’: ‘v1’, ‘k2’: ‘v2’, ‘k3’: ‘v3’)}
- xdict= {(‘k1’: ‘v1’), (‘k2’: ‘v2’), (‘k3’: ‘v3’)}
Question 94: What does a + within a regular expression stand for?
- Add two values
- At least one repetition
- Allow for no repetitions
- Concatenate two strings
Question 95: Why does this snippet of code not have good form?
try:
f = open(‘example.txt’)
f. read ()
print (‘File has been read’)
except:
print (‘File has not been read’)
- It should include a ‘finally’ block
- Its ‘except’ block will never execute
- It does not mention a specific exception type
- It should use an ‘else’ block to handle file errors
Question 96: Which of the following code snippets would complete this code so that it will identify the type of exception taking place?
try:
z = 3+input (‘Input a number: ‘)
- except NameError:
print(‘NameError’)
- except TypeError:
print(‘TypeError’)
- except IndexError:
print(‘IndexError’)
- except ValueError:
print(‘ValueError’)
Question 97: Which of the following statements about structured programs is true?
- They avoid using nesting loop control structures
- They apply class instances to accomplish a given task
- They arrange small units of code in the order of their execution
- They do not allow return arguments to be output from functions
Question 98: Which of the following would fix the syntax error in this code?
class Box:
def __init__ (self, length, width, height):
length=self. length
width=self. width
height=self. height
def __str__(self):
return ‘Length:’+str (self. length) +’ ‘+’Width:’+str (self. width) +’ ‘+’Height:’+str (self. height)
s1=Box (1,2,2)
print(s1)
- Modify the __init__ method to be
def init (self, length, width, height):
length=self. length
width=self. width
height=self. height
- Modify the __init__ method to be
def __init__ (self, length, width, height):
self. length=length
self. width=width
self. height=height
- Modify the __str__ method to be
def str(self):
return ‘Length:’+str (self. length) +’ ‘+’Width:’+str (self. width) +’ ‘+’Height:’+str (self. height)
- Modify the __str__ method to be
def __str__ (self, length, width, heigh):
return ‘Length:’+str (self. length) +’ ‘+’Width:’+str (self. width) +’ ‘+’Height:’+str (self. height)
Question 99: Complete the function named demorgan2 that will verify the following version of DeMorgan’s Law for sets A, B, and V:
V−(A∩B) =(V−A) ∪(V−B)
where:
A and B must be subsets of V
The minus sign indicates the set difference operation
∪
indicates the union operation
∩
indicates the intersection operation
Using this function definition line:
def demorgan2(V, A, B):
where A
and B
are subsets of V.
First compute: V−(A∩B)
Then compute: (V−A) ∪(V−B)
If the two are equal, return True; otherwise, return False.
Answer:(penalty regime: 0 %)
def demorgan2(V, A, B):
left_side = V. difference (A. intersection(B))
right_side = V. difference(A). union (V. difference(B))
if left_side == right_side:
return True
else:
return False
Question 100: Complete the function dictchk creates a new dictionary from an input dictionary as follows. Each key in the input dictionary is checked to see if it contains the character ‘k’. If so, the new dictionary is updated with the key:value pair. After all the keys have been checked, the new dictionary is returned.
Answer:(penalty regime: 0 %)
def dictchk(x):
new_dict = {}
for key in x:
if ‘k’ in key:
new_dict[key] = x[key]
return new_dict
Question 101: What should this expression result in an output of, and why?
print (2+10/5-4)
- 0, because division takes place before addition or subtraction
- 0.0, because division takes place before addition or subtraction
- 12, because addition and subtraction take place before division when using integers
- An error, because this is invalid Python syntax
Question 102: Assume this set of instructions is executed in the Repl.it run window.
z=int (input (‘Input a number: ‘))
y=’12’
print(z*y)
What will be the resulting output?
- The string ‘z12’
- 12 times the value input into the variable z
- z copies of ’12’ will be concatenated together and output
- An error, because the print expression mixes a string with a numeric value
Question 103: The goal of this function is to search for a key associated with an input value v given the input dictionary d:
def funcd (d, v):
for #complete this for statement
if d[key] == v:
return key
return dict ()
Which of the following statements would accomplish this goal?
- for d in key:
- for v in key:
- for key in v:
- for key in d:
Question 104: Assume that source.txt contains the data:
2
-3
5
7
8
-15
What will the screen output be after this code executes?
myfile = open(‘source.txt’)
a=-3
for line in myfile:
if a==int(line):
print(line)
break
myfile. close ()
- -3
- 2
- 7
- 8
Question 105: Which of the following strings, when inserted into this code, will generate a match if the code executes?
import re
pattern=’……[abc]\s\.’
s=#insert string here
print (re. search (pattern, s))
- s=’abcda.’
- s=’abcdea.’
- s=’……abc ‘
- s=’……abc.’
Question 106: What is the syntax error in this set of instructions?
def fexamp ():
a=2
return a
print(fexamp)
- There no input arguments to the function fexamp
- The print instruction should be print (fexamp ())
- The function definition line should be def fexamp:
- The function definition line should be def fexamp ()
Question 107: Which of the following is true about the ‘try-except’ block?
- Multiple errors can be handled within a single ‘except’ block
- Each ‘try’ block must be associated with exactly one ‘except’ block
- The ‘except’ block will not execute unless the type of error is specified
- An ‘else’ block must be included for handling the case where no error occurs
Question 108: Which of the following is a login password an example of?
- A Boolean variable
- A user input variable
- A fixed-length variable
- A programmer-initialized variable
Question 109: Assume that the file source.txt contains the data:
1
2.3
3.14
5
Which of the following lines would complete this code so that the variable s will contain the sum of the values in source.txt?
myfile = open(‘source.txt’)
s = 0
for line in myfile:
#Fill in the instruction(s) here
myfile. close ()
- s += line
- s += float(line)
- s = s + int(line)
- a = line
s = s + a
Question 110: What will the data type of the variable z be after this code runs?
f = open(‘example.txt’,’w’)
f. writes(‘1.5e03’)
f. close ()
f = open(‘example.txt’)
z=f. read ()
f. close ()
- float
- int
- list
- str
Question 111: When attempting to match a pattern string against a list of strings, using the compile method in the re module will do which of the following?
- Store the pattern to a file
- Convert the pattern into machine code
- Increase the efficiency of pattern matching
- Enable pattern matching using other programming languages
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It’s widely used in various fields like web development, data analysis, artificial intelligence, scientific computing, and more. Here’s a quick introduction to Python:
Key Features:
- Easy to Learn and Read: Python’s syntax is designed to be readable and straightforward, making it an excellent choice for beginners.
- Interpreted Language: Python code is executed line-by-line, which makes debugging easier and allows for quick development.
- Dynamic Typing: You don’t need to declare the type of a variable; Python infers it at runtime.
- Versatile: Python can be used for a variety of applications, including web development (using frameworks like Django or Flask), data analysis (using libraries like Pandas and NumPy), and automation.
Libraries and Frameworks:
- NumPy and Pandas: For numerical operations and data manipulation.
- Matplotlib and Seaborn: For data visualization.
- Requests: For making HTTP requests.
- Django and Flask: For web development.
Getting Started:
- Install Python: Download and install Python from python.org.
- IDE/Text Editor: Use an Integrated Development Environment (IDE) like PyCharm, or a text editor like VSCode.
- Write Code: Start coding in Python and explore libraries and frameworks based on your interests.
Overall, Python’s simplicity, versatility, and community support make it an excellent choice for both beginners and experienced developers alike. Whether you’re building a simple script or a complex application. Python offers the tools and resources you need to get the job done efficiently.