Tuesday, 24 June 2025

Python Coding challenge - Day 568| What is the output of the following Python Code?

 


Code Explanation:

1. Function Definition: Outer Function
def make_adder(n):
This defines a function named make_adder that takes one argument n.
n will be used to create a customized "adder" function.

2. Function Definition: Inner Function (Closure)
    def adder(x):
        return x + n
Inside make_adder, another function adder is defined.
adder takes a parameter x and returns the sum of x and n.
Note: n is not defined inside adder — it's taken from the enclosing scope (i.e., make_adder). This is called a closure.

3. Return the Inner Function
    return adder
make_adder returns the function adder, not the result of calling it.
The returned function "remembers" the value of n even after make_adder has finished executing.

4. Create a New Function using make_adder
add5 = make_adder(5)
Calls make_adder(5), which returns a function adder where n is permanently set to 5.
Now, add5 is a function that adds 5 to its input.

5. Call the New Function
print(add5(10))
Calls the add5 function with input 10.
Inside add5, x = 10 and n = 5 (from the closure).
So it computes 10 + 5 = 15.

print outputs:
15

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)