ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
funcs = {}
for name in ["inc", "dbl"]:
    if name == "inc":
        def op(v): return v + 1
    else:
        def op(v): return v * 2
    funcs[name] = op
print(funcs["inc"](5), funcs["dbl"](5), funcs["inc"].__name__)
  1. A. 10 10 op
  2. B. 6 10 op
  3. C. 6 10 inc
  4. D. 6 6 op

Correct answer: B. 6 10 op

Each def statement creates a new function object at the moment it runs, so the dict stores two different functions; the later rebinding of op does not affect the earlier one. Both are named op.

More Python Programming questions

Exams that ask this topic