ProgrammingHardAccenture pattern
What is printed?
What is printed?
def validate(f):
def wrapper(x):
if x < 0:
raise ValueError("negative")
return f(x)
return wrapper
@validate
def sqrtApprox(x):
return x ** 0.5
try:
print(sqrtApprox(-4))
except ValueError as e:
print("error:", e)
print(sqrtApprox(16))- A. error: negative 4.0
- B. -4.0 4.0
- C. error: negative error: negative
- D. 2.0 4.0
Correct answer: A. error: negative 4.0
sqrtApprox(-4) is wrapped by validate, which raises ValueError before ever computing a square root, caught and printed as 'error: negative'. sqrtApprox(16) passes validation and returns 16**0.5 = 4.0.
More Python Programming questions
- What is printed? python def makeFuncs(): return [lambda x, n=n: x n for n in range(1, 4)] fns = makeFuncs() print([f(2) for f in fns])
- What is printed? python def f(n): if n == 0: return 0 return 1 + f(n - 1) print(f(100))
- What is printed? python d = {} d.setdefault("a", []).append(1) d.setdefault("a", []).append(2) d.setdefault("b", []).append(3) print(d)
- What is printed? python class A: def len(self): return 0 a = A() print(bool(a)) if a: print("truthy") else: print("falsy")
- What is printed? python x = 10 class C: x = 20 def m(self): return x c = C() print(c.m(), C.x)
- What is printed? python def f(x, y=10): def g(): return x + y y = 20 return g() print(f(1))