A closure in Python is a nested function that remembers and has access to variables from its outer (enclosing) function's scope, even after the outer function has finished executing.
The Three Conditions for a Closure: For a closure to exist, three specific criteria must be met:
There must be a nested function (a function inside a function).
The nested function must reference a value belonging to the outer function.
The outer function must return the nested function.
def make_multiplier(x):
# The outer function takes 'x'
def multiplier(y):
# The inner function references 'x' from the outer scope
return x * y
# Returns the inner function object
return multiplier
# Create two custom functions
times_two = make_multiplier(2)
times_three = make_multiplier(3)
# Use the closures
print(times_two(10)) # Output: 20
print(times_three(10)) # Output: 30