ProgrammingModerateAccenture · Capgemini pattern
What is printed?
What is printed?
class Box:
def __len__(self):
return 0
b = Box()
print(bool(b), "yes" if b else "no", len([b, b]))- A. True yes 2
- B. False no 2
- C. True no 2
- D. False no 0
Correct answer: B. False no 2
When a class has no __bool__, truth testing falls back to __len__: a length of 0 is falsy, so bool(b) is False and the conditional picks "no". The list [b, b] still holds two elements, so its len is 2. Objects are truthy by default only when neither __bool__ nor __len__ is defined.
More Python Programming questions
- What is printed? python a = [3, 1, 4, 1, 5] a.insert(-1, 9) print(a, a.index(1), a.pop(), a.count(1))
- What is printed? python def g(): print("start", end=" ") yield 1 print("mid", end=" ") yield 2 it = g() print("made", end=" ")…
- What is printed? python x = 1 def f(flag): if flag: x = 2 return x print(f(True), end=" ") try: print(f(False)) except UnboundLocalError…
- What is printed? python class A: pass class B(A): pass try: class C(A, B): pass print("ok", end=" ") except TypeError: print("TypeError"…
- What is printed? python class R: def iter(self): print("it", end=" ") return iter([1, 2, 3]) r = R() print(2 in r, 5 in r)
- What is printed? python d = {1: "a", 2: "b"} for k in d: d[k] = d[k] 2 try: for k in d: d[k 10] = "x" except RuntimeError: print("RE"…