Question
In Python, what will be the output of the following code
snippet, considering scope rules? x = 5               def func():    x = 10    def inner():        nonlocal x        x += 1        return x    return inner()  print(func())Solution
The code demonstrates the use of the nonlocal keyword in Python, which allows a variable defined in an enclosing (but not global) scope to be modified. Here’s a breakdown:
- The variable x = 5 is declared globally.
- Inside the func() function, a local x = 10 is declared.
- Within the nested inner() function, the nonlocal x statement is used. This tells Python that x refers to the x variable in the enclosing func() scope (not the global scope).
- The x is incremented by 1 (x += 1), updating it to 11.
- The inner() function returns x, and func() also returns the result from inner(). Hence, the final output is 11.
- Option A (6): This assumes that nonlocal affects the global x. However, nonlocal only modifies variables in the closest enclosing non-global scope. Thus, the global x = 5 remains unchanged.
- Option C (10): This would be true if no modification occurred to the local x inside the inner() function. However, x is incremented by 1 due to nonlocal.
- Option D (UnboundLocalError): This error would occur if nonlocal was omitted and x was incremented without declaration, as Python would not recognize it as being defined in the current scope.
- Option E (None): This would result if func() or inner() explicitly returned None. Since the function returns x, this is incorrect.
Which planet is known as “lord of the heavens”?
Nissan automobile has been embroiled in a legal battle with a state government in India over the issue of incentive to be paid. The state Government is ...
On which date Savita Kanswal (Uttarakashi) and many mountaineers died in Draupadi Ka Danda-2 due to a massive avalanche?
Mamluk Dynasty was ended by which of the following rulers?Â
Match the following athletes with their respective sports:Â
Which of the following pairs is/are correctly matched regarding National Highways and the cities they connect?
I) NH 129 - Dimapur to Numaligarh<...
Who is the current chairman of LIC (Life Insurance Corporation) of India?
Recently norms related to Minimum Alternative Tax (MAT) has been relaxed for companies facing insolvency process. The provision of MAT is in:
A is 5 years younger to B, and B is 3 times older than C. If C was 10 years old four years ago, what will be the age of A after 6 years?
Recently Prime Minister commissioned a submarine in Mumbai which was totally made in India. Name the submarine