233 views
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?

  1. $\verb|30 20 10|$
     
  2. $\verb|30 30 10|$
     
  3. $\verb|30 30 30|$
     
  4. $\verb|20 20 10|$

1 Answer

0 0 votes

Step-by-Step Logic:

  1. Global Level: $\verb|x|$ is initialized to $\mathbf{10}$.
     
  2. $\verb|outer_func|$ Execution: A local variable $x$ is created in the local scope of $\verb|outer_func|$ and assigned $\mathbf{20}$.
     
  3. $\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}.$
       
  4. Back in $\verb|outer_func()|$ : Since inner_func modified the nonlocal $\verb|x|$, the $\verb|print(x)|$ here also outputs $\mathbf{30}$.
     
  5. 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}$.
Answer:
Position:
Show:

Related questions

0 0 votes
1 1 answer
244
244 views
GO Classes asked Jan 7
244 views
You have a dataset of students with two attributes: $\verb|Grade|$ (A, B, C) and $\verb|Name|$ (Alphabetical). The data is currently sorted alphabetically by $\verb|Name|...
1 1 vote
1 1 answer
219
219 views
GO Classes asked Jan 7
219 views
Consider a Full Binary Tree (a tree where every node has either $0$ or $2$ children). If the tree has $L$ leaf nodes, which of the following expressions correctly represe...
0 0 votes
1 1 answer
215
215 views
GO Classes asked Jan 7
215 views
Suppose you are implementing a Stack using two Queues, $Q 1$ and $Q 2$. To maintain the LIFO (Last-In, First-Out) property of a stack during a 'push' operation, you decid...
1 1 vote
1 1 answer
231
231 views
GO Classes asked Jan 7
231 views
A student attempts to use various Python collections as keys in a dictionary to map them to their respective sums. d = {} try: d[(1, 2, [3])] = 6 except TypeError: ...