ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class A:
    def __len__(self):
        return 0
a = A()
print(bool(a))
if a:
    print("truthy")
else:
    print("falsy")
  1. A. True truthy
  2. B. False falsy
  3. C. True falsy
  4. D. False truthy

Correct answer: B. False falsy

Without a __bool__ method, Python falls back to __len__ for truthiness: a length of 0 is treated as falsy, so bool(a) is False and the if-statement takes the else branch.

More Python Programming questions

Exams that ask this topic