Skip to content
CodeKruPro

A counter built with a closure and nonlocal

Predict the outputMediumPython only
main.py
def make_counter():
    count = 0

    def inc():
        nonlocal count
        count += 1
        return count

    return inc

c1 = make_counter()
c2 = make_counter()
print(c1(), c1(), c1())
print(c2())

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in