+ 2

Function argument holds unexpected value: can you explain why?

Hello guys, I’ve encountered this question in Python challenge session. Can someone explain why the output is 1? I would expect a += 1 makes it 2. a = 1 def func(num=a): print(num) a += 1 func()

1st May 2021, 7:25 AM
Lucie
Lucie - avatar
4 Answers
+ 5
This has to do with compilation time parsing. Which is when the initial definition of the function is created. The py file is parsed multiple times during compilation. When it is first parsed in a top down fashion the value of the global variable name a is first found to be 1. Directly after that the function is created and the value of a is 1 at its time of creation. This will set the functions local variable name num in the functions locals dict to the default value of 1. So when compilation finishes and the program is ran the local variable num will have the value of 1 and the global variable a will have the value of 2. Hard to explain without graphics, and probably not the best or most accurate description, but hopefully you can understand the gist of it.
1st May 2021, 7:51 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
Thank you ChaoticDawg. Your answer is great. It’s a bit hard concept to grasp for a beginner, but I think I get it now. So the function adopts the value at the moment that it is created and sets it as a local variable. The value doesn’t change when the function is called. And if a is not declared before we define the function, the code doesn’t work at all.
1st May 2021, 9:46 AM
Lucie
Lucie - avatar
+ 2
It will first give output 1... then increment value.
1st May 2021, 7:28 AM
Sâùtôsh
Sâùtôsh - avatar
+ 2
the code is like this in python: a=1 def func(num=1): print(num) a += 1 func()
1st May 2021, 8:49 AM
arvin
arvin - avatar