Saylor Academy CS105: Introduction to Python Final Exam 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 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 3: 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 4: 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 5: 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 6: 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 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: 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 9: 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 10: Assume this set of instructions is executed in the Repl.it run window.
z=intinput(‘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 11: 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 12: 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 13: 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 14: Which of the following can be used to refer to specific values contained within a list?
- Container
- Index
- Operator
- Sequence
Question 15: 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 16: 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 17: 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 18: 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 19: Which punctuation mark must the definition line for a function must end with?
- Colon
- Comma
- Period
- Semicolon
Question 20: 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 21: 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 22: 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 23: 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 24: 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 25: 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 se
- xdict[‘k3’] refers to a tuple
Question 26: 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 27: 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 28: What will the data type of the variable z be after this code runs?
f=open(‘example.txt’,’w’)
f.write(‘1.5e03’)
f.close()
f=open(‘example.txt’)
z=f.read()
f.close()
- float
- int
- list
- str
Question 29: Which of the following segments of code is this code segment most similar to?
myfile = open(‘source.txt’)
print(myfile.read())
myfile.close()
- myfile = open(‘source.txt’)
for line in myfile:
print(myfile.readlines())
myfile.close()
- myfile = open(‘source.txt’)
for line in myfile:
print(readlines())
myfile.close()
- myfile = open(‘source.txt’)
for line in myfile:
print(line)
myfile.close()
- myfile = open(‘source.txt’)
for line in myfile:
print(myfile.read())
myfile.close()
Question 30: 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 31: 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
Question 32: 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 33: 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 34: Which of the following is true about the ‘try-except’ block?
- a.Multiple errors can be handled within a single ‘except’ block
- b.Each ‘try’ block must be associated with exactly one ‘except’ block
- c.The ‘except’ block will not execute unless the type of error is specified
- d.An ‘else’ block must be included for handling the case where no error occurs
Question 35: 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 36: Object-oriented programming uses methods for defining and accomplishing tasks. Which of the following does procedural programming use?
- Dictionaries
- Functions
- Snippets
- Variables
Question 37: If two different objects from the same class are instantiated, which of the following will be true?
- Their methods must be different
- They will have different attributes
- Their data attributes can take on different values
- They cannot both be used as inputs to a function
Question 38: 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 39: 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:
Question 40: 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:
def listprod(x):
p=1
for i in x:
p=p*i
return p
Question 41: 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:
def distprop(A,B,C):
if A.union(B.intersection(C)) == (A.union(B)).intersection(A.union(C)):
return True
else:
return False