Welcome to the “Closures” tutorial!
Overview
A closure captures variables from its enclosing scope.
Example
def make_multiplier(x):
def multiplier(n):
return x * n
return multiplier
times3 = make_multiplier(3)
print(times3(5)) # 15
multiplier
remembersx
even aftermake_multiplier
finishes.
Key Takeaways
- Closures allow stateful functions without globals.
- Useful for factory functions and callbacks.
Happy coding!
Comments
Post a Comment