All quizzesHard
Expert Mastery — Series 2
Preview — 3 of 10 questions
What is the output of the following code?
javascript
import types
class Animal:
pass
def bark(self):
return f"{self.name} barks"
a = Animal()
a.name = "Rex"
a.speak = bark
print(a.speak())
a.speak2 = types.MethodType(bark, a)
print(a.speak2())ARex barks, then Rex barks
BTypeError: speak() missing 1 required positional argument: 'self', then the same TypeError again for speak2
CTypeError: bark() missing 1 required positional argument: 'self', then Rex barks
DAttributeError: 'Animal' object has no attribute 'speak', then Rex barks
What is the output of the following code?
javascript
import sys
old_limit = sys.getrecursionlimit()
sys.setrecursionlimit(50)
def recurse(n):
return recurse(n + 1)
try:
recurse(0)
except RecursionError:
print("RecursionError caught")
sys.setrecursionlimit(old_limit)
print("continues")ARecursionError caught, then continues
BThe program crashes entirely — sys.setrecursionlimit cannot be lowered below the default at runtime.
CRecursionError caught, then a RuntimeError is raised immediately after, since the recursion limit was never restored.
DNothing is caught — RecursionError is a SystemExit subclass that bypasses ordinary except blocks.
What is the output of the following code?
javascript
code = "result = x + y"
namespace = {"x": 10, "y": 5}
exec(code, {"__builtins__": {}}, namespace)
print(namespace["result"])
try:
exec("open('file.txt')", {"__builtins__": {}}, {})
except NameError as e:
print("NameError:", e)A15, then open('file.txt') executes normally, since exec() always has full access to the real builtins regardless of the namespace passed in.
BTypeError: exec() takes at most 2 arguments
CNameError: name 'x' is not defined — passing separate globals/locals dicts to exec() always breaks variable lookup.
D15, then NameError: name 'open' is not defined
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.