Question discussion

What is the output of the following Python code?def make(): n = 0 def inc(): nonlocal n n += 1 return n return inc a = make(); b = make() p…

1572Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Python code?

def make():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc
a = make(); b = make()
print(a(), a(), b())
  • A1 2 3
  • B1 2 2
  • C1 1 1
  • D1 2 1
Correct answer: D

Explanation

Each call to make() creates its own enclosing variable n, so a counts 1, 2 while b starts afresh at 1.

Discussion 0

Nobody has replied yet. Start the discussion!