1 1 vote Consider the following code snippet where a function is nested within another: x = 10 def outer_func(): x = 20 def inner_func(): nonlocal x x = 30 print(x, end=" ") inner_func() print(x, end=" ") outer_func() print(x)What will be the exact output printed by the execution of this script?$\verb|30 20 10|$ $\verb|30 30 10|$ $\verb|30 30 30|$ $\verb|20 20 10|$ Programming in Python goclasses python-&-dsa goclasses-da-dpp goclasses-da-dpp-day-82 goclasses-python-&-dsa-practice-questions + – GO Classes 233 views answer comment Share Follow Print 0 reply Please log in or register to add a comment.
0 0 votes Step-by-Step Logic:Global Level: $\verb|x|$ is initialized to $\mathbf{10}$. $\verb|outer_func|$ Execution: A local variable $x$ is created in the local scope of $\verb|outer_func|$ and assigned $\mathbf{20}$. $\verb|inner_func|$ Execution: *The $\verb|nonlocal x|$ keyword tells Python that the $\verb|x|$ inside $\verb|inner_func|$ refers to the variable in the nearest enclosing scope $($which is $\verb|outer_func|)$, not the global scope. $\verb|x = 30|$ changes the $\verb|x|$ in $\verb|outer_func|$ from $20$ to $\mathbf{30}.$ $\verb|print(x)|$ inside $\verb|inner_func|$ outputs $\mathbf{30}.$ Back in $\verb|outer_func()|$ : Since inner_func modified the nonlocal $\verb|x|$, the $\verb|print(x)|$ here also outputs $\mathbf{30}$. Back to Global: The global $\verb|x|$ was never touched because $\verb|nonlocal|$ only looks at enclosing function scopes. Therefore, the final $\verb|print(x)|$ outputs the original $\mathbf{10}$. GO Classes answered Jan 7 GO Classes comment Share Follow 0 reply Please log in or register to add a comment.