Tuesday, 21 April 2026

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

 


Code Explanation:

๐Ÿงฉ 1. Function Definition: outer
def outer():
This defines a function named outer.
It acts as an enclosing (parent) function.

๐Ÿ“ฆ 2. Variable Initialization
    x = 10
A local variable x is created inside outer.
Initial value of x is 10.

๐Ÿ” 3. Inner Function Definition
    def inner():
A nested function named inner is defined inside outer.
It has access to variables of outer (like x).

๐Ÿ”— 4. Using nonlocal
        nonlocal x
nonlocal means:
“Use the variable x from the nearest enclosing scope (outer function), not create a new one.”
Without nonlocal, modifying x would cause an error.

➕ 5. Modify the Variable
        x += 5
Adds 5 to the existing value of x.
Since x is nonlocal, it updates the outer function’s x.

๐Ÿ”™ 6. Return Updated Value
        return x
Returns the updated value of x.

๐Ÿ“ค 7. Return Inner Function
    return inner
The outer function returns the inner function itself, not its result.
This creates a closure (function + its environment).

๐ŸŽฏ 8. Create Function Instance
f = outer()
Calls outer(), which returns inner.
Now f becomes a reference to inner, with x = 10 preserved.

๐Ÿ–จ️ 9. Function Calls and Output
print(f(), f())
First Call: f()
x = 10
x += 5 → 15
Returns 15
Second Call: f()
x = 15 (value persists due to closure)
x += 5 → 20
Returns 20

✅ Final Output
15 20

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (249) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (29) Azure (10) BI (10) Books (262) Bootcamp (9) C (78) C# (12) C++ (83) Course (87) Coursera (300) Cybersecurity (30) data (5) Data Analysis (32) Data Analytics (22) data management (15) Data Science (349) Data Strucures (17) Deep Learning (154) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (71) Git (10) Google (51) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (42) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (287) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (14) PHP (20) Projects (32) pytho (1) Python (1316) Python Coding Challenge (1130) Python Mistakes (51) Python Quiz (482) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (49) Udemy (18) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)