ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def counter():
count = 0
def inc():
nonlocal count
count += 1
return count
def peek():
return count
return inc, peek
inc, peek = counter()
inc(); inc()
inc2, peek2 = counter()
inc2()
print(peek(), peek2(), inc())- A. 3 1 3
- B. 2 1 1
- C. 2 1 3
- D. 0 0 3
Correct answer: C. 2 1 3
inc and peek of the same counter() call share one cell; the second call creates an independent cell. peek() sees 2 and peek2() sees 1; print evaluates arguments left to right, so the final inc() returns 3 after peek() already read 2.
More Python Programming questions
- What is printed? python x = 0 def outer(): x = 1 def mid(): def inner(): nonlocal x x += 10 return x return inner() r = mid() return r, x…
- What is printed? python def f(): try: print(y, end=" ") except NameError as e: print(type(e).name, end=" ") y = 1 y = 5 f() print(y)
- What is printed? python def gen(): for i in range(3): yield lambda: i a = [f() for f in gen()] b = [f() for f in list(gen())] print(a, b)
- What is printed? python x = 1 g = (x y for y in range(3)) x = 2 print(list(g))
- What is printed? python xs = [1, 2, 3] g = (a 10 + b for a in xs for b in xs) xs = [10, 20] print(sum(g))
- What is printed? python def g(): yield 1 yield 2 it = g() for v in it: print(v, end=" ") break for v in it: print(v, end=" ")…