Labs ICT
🎓 SIWES/IT Login

Closures

1 min read | Python Tutorial
🎓

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

Basic Closure

A closure is a nested function that remembers variables from its enclosing scope even after the outer function has finished executing. It's created when the inner function is returned.

def multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply

times3 = multiplier(3)
print(times3(7))

Counter Closure

Closures can maintain state across calls. The inner function captures and modifies a variable from the outer scope, which persists between invocations.

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

c = make_counter()
print(c())
print(c())
print(c())