๐น Step 1: val = 5
A global variable val is created with the value 5.
๐น Step 2: Function definition
def demo(val = val + 5):When Python defines the function, it evaluates all default argument expressions immediately — not when the function is called.
So here:
-
It tries to compute val + 5
-
But val inside this expression is looked up in the current (global) scope — where val = 5.
✅ Hence, the default value becomes val = 10.
๐น Step 3: Function call
demo()When the function runs:
-
No argument is passed, so it uses the default value val = 10.
-
Then it prints 10.
✅ Output:
⚠️ Important Note:
If the global val didn’t exist before defining the function, Python would raise a NameError because it can’t evaluate val + 5 at definition time.
๐ Summary
| Step | Explanation | Result |
|---|---|---|
| Global variable | val = 5 | Creates a variable |
| Default argument evaluated | val + 5 → 10 | At definition time |
| Function call | demo() | Uses default |
| Output | 10 | ✅ |


0 Comments:
Post a Comment