+ 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()
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.
+ 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.
+ 2
It will first give output 1...
then increment value.
+ 2
the code is like this in python:
a=1
def func(num=1):
print(num)
a += 1
func()