python closures code example
Example 1: python define a function within a function
def print_msg(msg):
def printer():
print(msg)
return printer
another = print_msg("Hello")
another()
Example 2: closures in python
def make_summer():
data = []
def summer(val):
data.append(val)
_sum = sum(data)
return _sum
return summer
Example 3: closures in python
def main():
def build_message(name):
msg = f'Hello {name}'
return msg
name = input("Enter your name: ")
msg = build_message(name)
print(msg)
if __name__ == "__main__":
main()