Friday, 16 May 2025

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

 


Code Explanation:

1. Global Scope (x = 10)
x = 10
The first x = 10 creates a variable x in the global scope (outside any function).

This value of x is available throughout the entire program unless overridden in a local scope.

2. Defining outer()
def outer():
    x = 20
    def inner(): nonlocal x; x = 30
    inner(); print(x)
Inside outer(), there's another variable x = 20, which is local to outer(). This means that x inside the outer() function initially takes the value 20.

Defining the inner() function:

def inner(): nonlocal x; x = 30
inner() is a nested function inside outer().

The nonlocal x statement tells Python to look for x in the nearest enclosing scope (which is outer()), rather than creating a new x in inner().

The x = 30 changes the value of x in the enclosing outer() function to 30.

Calling inner():

inner(); print(x)
When inner() is called, it updates the value of x in the outer() function to 30.

After inner() runs, x inside outer() is now 30.

The print(x) inside outer() will print the value of x from the outer() scope, which is now 30.

3. Calling outer()
outer(); print(x)
Executing outer():

outer() is called, and inside it, x becomes 20 initially.

inner() runs and modifies x to 30.

So, the first print statement inside outer() prints 30.

The final print(x):

This print statement is outside outer(), so it refers to the global x.

The global x was never modified by outer(). It still holds the value 10.

Hence, this print statement prints 10.

Final Output
30
10


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (161) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (254) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (225) Data Strucures (14) Deep Learning (75) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (48) 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 (197) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1219) Python Coding Challenge (898) Python Quiz (348) 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)