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]))
  1. A. True yes 2
  2. B. False no 2
  3. C. True no 2
  4. 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

Exams that ask this topic