Answers for "closures in python"

1

closures in python

#!/usr/bin/env python

def make_counter():

    count = 0
    def inner():

        nonlocal count
        count += 1
        return count

    return inner


counter = make_counter()

c = counter()
print(c)

c = counter()
print(c)

c = counter()
print(c)
Posted by: Guest on June-09-2021
1

closures in python

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

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

    return printer  # returns the nested function


# Now let's try calling this function.
# Output: Hello
another = print_msg("Hello")
another()
Posted by: Guest on July-19-2020
0

closures in python

# Python program to illustrate
# nested functions
def outerFunction(text):
    text = text
 
    def innerFunction():
        print(text)
 
    innerFunction()
 
if __name__ == '__main__':
    outerFunction('Hey!')
Posted by: Guest on June-08-2021
0

closures in python

def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier


# Multiplier of 3
times3 = make_multiplier_of(3)

# Multiplier of 5
times5 = make_multiplier_of(5)

# Output: 27
print(times3(9))

# Output: 15
print(times5(3))

# Output: 30
print(times5(times3(2)))
Posted by: Guest on July-14-2020
0

closures in python

def make_summer():

    data = []

    def summer(val):

        data.append(val)
        _sum = sum(data)

        return _sum

    return summer
Posted by: Guest on June-09-2021
0

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()
Posted by: Guest on June-09-2021
0

closures in python

def make_counter():

    count = 0
    def inner():

        nonlocal count
        count += 1
        return count

    return inner
Posted by: Guest on June-09-2021
0

closures in python

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

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

    printer()

# We execute the function
# Output: Hello
print_msg("Hello")
Posted by: Guest on June-08-2021
0

closures in python

#!/usr/bin/env python

def make_printer(msg):

    msg = "hi there"

    def printer():
        print(msg)

    return printer


myprinter = make_printer("Hello there")
myprinter()
myprinter()
myprinter()
Posted by: Guest on June-09-2021
0

closures in python

#!/usr/bin/env python


def make_summer():

    data = []

    def summer(val):

        data.append(val)
        _sum = sum(data)

        return _sum

    return summer

summer = make_summer()

s = summer(1)
print(s)

s = summer(2)
print(s)

s = summer(3)
print(s)

s = summer(4)
print(s)
Posted by: Guest on June-09-2021

Python Answers by Framework

Browse Popular Code Answers by Language