1.
Which of the following Python features allows you to define a function that can be paused and resumed, maintaining its state between executions?
Correct Answer
B. Generators
Explanation
Generators are a feature in Python that allows you to define a function that can be paused and resumed, maintaining its state between executions. This is done using the yield statement. When the generator's function is called, it returns an iterator object but does not start execution immediately. When the next() method is called on the iterator, the function executes until it encounters the yield statement, returning the yielded value. The function can be resumed from where it left off when next() is called again.
2.
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
Correct Answer
E. An exception is thrown
Explanation
The code creates an instance of the NumFactory class with an initial value of 2. It then iterates over all the attributes of the instance using the dir() function. For each attribute, it checks if it is callable (a method) using the callable() function. If it is callable, it calls the method. However, there are no methods defined in the NumFactory class that can be called. Therefore, an exception is thrown when trying to call a non-existent method.
3.
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))
Correct Answer
A. +++1 some info+++
Explanation
The function print_header is defined with a parameter "str". Inside the function, it prints "+++" followed by the value of "str" followed by "+++".
Then, the function is called with an argument "%d %s" % (print_header.category, print_header.text). This means that the value of print_header.category is substituted for "%d" and the value of print_header.text is substituted for "%s".
Therefore, the output will be "+++1 some info+++".
4.
What gets printed?
names1 = ['Amir', 'Barry', 'Chales', 'Dao']
names2 = [name.lower() for name in names1]
print names2[2][0]
Correct Answer
C. C
Explanation
The code creates a new list called names2, which contains the lowercase versions of each name in names1. The expression names2[2] accesses the third element of names2, which is "chales". The expression names2[2][0] then accesses the first character of "chales", which is "c". Therefore, the output will be "c".
5.
What gets printed?
names1 = ['Amir', 'Barry', 'Chales', 'Dao']
loc = names1.index("Edward")
print loc
Correct Answer
E. An exception is thrown
Explanation
The code attempts to find the index of "Edward" in the list names1 using the index() method. Since "Edward" is not in the list, the index() method raises a ValueError exception. As a result, the program does not print an index; instead, it throws an exception with a message indicating that "Edward" is not in the list.
6.
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()
Correct Answer
D. __main__
Explanation
The code defines a class called Person with an empty constructor and a method called getAge. When the program is run, an instance of the Person class is created and the getAge method is called on that instance. The getAge method prints the value of __name__, which is a special variable that holds the name of the current module. In this case, since the program is run directly as the main module, the value of __name__ is "__main__". Therefore, the output of the program will be "__main__".
7.
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
Correct Answer
C. 13
Explanation
The given code uses regular expressions to match and search for the pattern "back" in different strings. The first if statement uses the match() method to check if the pattern matches the string "backup.txt", which is true. Therefore, sum is incremented by 1. The second if statement also uses the match() method, but since the pattern does not match the string "text.back", this if statement is false and does not increment sum. The third if statement uses the search() method to check if the pattern is found anywhere in the string "backup.txt", which is true. Therefore, sum is incremented by 4. The fourth if statement also uses the search() method and matches the pattern in the string "text.back", so sum is incremented by 8. The final value of sum is 13, which is printed.
8.
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
Correct Answer
C. 600 400
Explanation
The initial balance of the account is 100. Then, 800 is deposited, resulting in a balance of 900. After that, 500 is withdrawn, resulting in a balance of 400. The account balance is then increased by 200, resulting in a balance of 600. When the account is loaded from the archive file, the balance remains the same at 600. Therefore, the numbers that get printed are 600 and 400.
9.
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)
Correct Answer
E. Error is generated by program
Explanation
The correct answer is "Error is generated by program". This is because the child class constructor does not call the parent class constructor, so the v1 attribute of the parent class is not initialized. Therefore, when trying to print obj.v1, an error is generated.
10.
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)
Correct Answer
B. False
Explanation
The given code will not successfully print the days and then the months. The code is missing a closing parenthesis ")" after "months" in the print statement. Therefore, it will result in a syntax error.
11.
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
Correct Answer
C. 3
Explanation
The code will print 3. This is because the condition in the third elif statement is true. The condition is "not x or y or not y and x". Since x is True and y is False, the condition "not y and x" evaluates to True. Therefore, the print statement inside the third elif block will be executed.
12.
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()
Correct Answer
B. False
Explanation
In Python 2.6 or earlier, the code as written would raise a SyntaxError because the syntax used for handling multiple exceptions in a single except block is incorrect. The correct syntax for catching multiple exceptions in Python 2.6 or earlier is to use a tuple of exceptions:
python
Copy code
try: accessSecureSystem() except (AccessError, SecurityError): print "error type 1" continueWork()
With this corrected syntax, the code will print "error type 1" if accessSecureSystem raises an exception of either AccessError or SecurityError type. If no exception is raised, it will simply continue to continueWork().
13.
What gets printed?
kvps = {"user","bill", "password","hillary"}
print kvps['password']
Correct Answer
E. Nothing. Python syntax error
Explanation
The given code tries to access the value associated with the key 'password' in the dictionary kvps. However, the dictionary declaration is incorrect. In Python, dictionaries are declared using curly braces ({}) and colons (:). The correct declaration should be kvps = {'user': 'bill', 'password': 'hillary'}. Therefore, when trying to access the value using kvps['password'], it will result in a syntax error.
14.
What gets printed?
def simpleFunction():
"This is a cool simple function that returns 1"
return 1
print simpleFunction.__doc__[10:14]
Correct Answer
E. Cool
Explanation
The provided Python code defines a function called simpleFunction with a docstring describing its purpose. The print statement extracts a specific substring (characters 10 to 13) from this docstring and prints it. In this instance, it prints the word "cool," offering a succinct representation of the function's nature as outlined in the docstring. The code demonstrates the use of docstrings for documenting functions and extracting information from them.
15.
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
Correct Answer
C. 13
Explanation
The code uses regular expressions to check if the pattern "back" is present in the given strings. The first two conditions use the match() function, which checks if the pattern matches the entire string. Since "backup.txt" starts with "back", the first condition is true and sum is incremented by 1. However, "text.back" does not start with "back", so the second condition is false and sum remains unchanged. The next two conditions use the search() function, which checks if the pattern is present anywhere in the string. Both "backup.txt" and "text.back" contain "back", so both conditions are true and sum is incremented by 4 and 8 respectively. Therefore, the final value of sum is 1 + 4 + 8 = 13.