What will be the output of the following code?def outer_function():x =...
The outer_function defines a variable x and calls the inner_function, which uses the nonlocal keyword to access and modify the outer variable x. After calling inner_function, the value of x is 15, which is printed as the output.
What will be the output of the following code?def outer_function():x =...
Explanation:
The code provided defines two functions: outer_function and inner_function.
In the outer_function, a variable named x is defined and assigned a value of 10.
The inner_function is defined within the outer_function. It uses the nonlocal keyword to indicate that the variable x being used is the same as the one defined in the outer_function, not a new local variable.
Inside the inner_function, the value of x is changed to 5 and then printed.
After the inner_function is called, the value of x is printed again.
Output:
The output of the code will be:
15
10
Explanation of Output:
- When the inner_function is called, it changes the value of x to 5 using the nonlocal keyword.
- So, the first print statement inside the inner_function will output 5.
- After the inner_function is called, the value of x is still accessible in the outer_function.
- Therefore, when the second print statement is executed in the outer_function, the value of x is 15 because it was changed to 5 in the inner_function.