ProgrammingHardTCS NQT · Wipro pattern

What is printed?

What is printed?
ops = {}
for name in ['add', 'mul']:
    ops[name] = lambda x, y, n=name: x + y if n == 'add' else x * y
print(ops['add'](2, 3), ops['mul'](2, 3))
  1. A. 5 6
  2. B. 5 5
  3. C. 6 6
  4. D. 5 2

Correct answer: A. 5 6

The default argument n captures each name when its lambda is created, so add and mul pick the right branch. 2 + 3 = 5 and 2 * 3 = 6.

More Python Programming questions

Exams that ask this topic