python closures code example

Example 1: python define a function within a function

def print_msg(msg): # This is the outer enclosing function
    
    def printer():# This is the nested function
        print(msg)

    return printer  # this got changed

# Now let's try calling this function.
# Output: Hello
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

#!/usr/bin/env 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()