ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
class N:
    def __init__(self, v):
        self.v = v
    def __bool__(self):
        return self.v != 0
n1 = N(0)
n2 = N(5)
print(bool(n1), bool(n2))
if n1:
    print("n1 true")
else:
    print("n1 false")
  1. A. True False n1 true
  2. B. False True n1 false
  3. C. True True n1 true
  4. D. False False n1 false

Correct answer: B. False True n1 false

__bool__ defines truthiness directly: n1.v is 0 so bool(n1) is False, n2.v is 5 so bool(n2) is True. The if statement calls __bool__ on n1 too, taking the else branch and printing 'n1 false'.

More Python Programming questions

Exams that ask this topic