closures in python

Solutions on MaxInterview for closures in python by the best coders in the world

showing results for - "closures in python"
Daysha
21 Jan 2019
1#!/usr/bin/env python
2
3def make_counter():
4
5    count = 0
6    def inner():
7
8        nonlocal count
9        count += 1
10        return count
11
12    return inner
13
14
15counter = make_counter()
16
17c = counter()
18print(c)
19
20c = counter()
21print(c)
22
23c = counter()
24print(c)
25
Fernando
05 May 2019
1# Python program to illustrate
2# nested functions
3def outerFunction(text):
4    text = text
5 
6    def innerFunction():
7        print(text)
8 
9    innerFunction()
10 
11if __name__ == '__main__':
12    outerFunction('Hey!')
13
Erica
06 Jan 2017
1#!/usr/bin/env python
2
3def make_printer(msg):
4
5    msg = "hi there"
6
7    def printer():
8        print(msg)
9
10    return printer
11
12
13myprinter = make_printer("Hello there")
14myprinter()
15myprinter()
16myprinter()
17
Soan
15 Jan 2019
1#!/usr/bin/env python
2
3
4def main():
5
6    def build_message(name):
7
8        msg = f'Hello {name}'
9        return msg
10
11    name = input("Enter your name: ")
12    msg = build_message(name)
13
14    print(msg)
15
16
17if __name__ == "__main__":
18    main()
19
Auguste
18 Mar 2016
1def make_counter():
2
3    count = 0
4    def inner():
5
6        nonlocal count
7        count += 1
8        return count
9
10    return inner
11
Emilie
09 Jan 2019
1def print_msg(msg):
2    # This is the outer enclosing function
3
4    def printer():
5        # This is the nested function
6        print(msg)
7
8    printer()
9
10# We execute the function
11# Output: Hello
12print_msg("Hello")
Adrian
28 Aug 2017
1def make_summer():
2
3    data = []
4
5    def summer(val):
6
7        data.append(val)
8        _sum = sum(data)
9
10        return _sum
11
12    return summer
13
Montserrat
13 Jan 2019
1#!/usr/bin/env python
2
3
4def make_summer():
5
6    data = []
7
8    def summer(val):
9
10        data.append(val)
11        _sum = sum(data)
12
13        return _sum
14
15    return summer
16
17summer = make_summer()
18
19s = summer(1)
20print(s)
21
22s = summer(2)
23print(s)
24
25s = summer(3)
26print(s)
27
28s = summer(4)
29print(s)
30