Step 1: Loop Execution
-
The loop runs 3 times — for i = 0, 1, and 2.
-
Each time, x is assigned the value of i.
-
After the loop finishes, x remains as the last value assigned → x = 2.
So now:
x = 2๐น Step 2: Function Definition
This defines a function named test, but it doesn’t execute yet.
๐น Step 3: Function Call
test()
When test() runs:
-
Python looks for the variable x inside the function (local scope).
-
It doesn’t find one, so it looks outside the function (global scope).
-
There it finds x = 2.
✅ Output:
2
Key Concept — Scope:
-
Local scope: Variables declared inside a function.
-
Global scope: Variables declared outside functions.
-
If a function doesn’t have a local variable with the same name, it uses the global variable.
Final Output → 2


0 Comments:
Post a Comment