Dec-19-2018, 12:21 PM
I cannot find the problem with the following piece of code-
>>> def func(n=[]): #playing around pass >>> func([1,2,3]) >>> func() >>> n
Is there an error in the code?
|
Dec-19-2018, 12:21 PM
I cannot find the problem with the following piece of code-
>>> def func(n=[]): #playing around pass >>> func([1,2,3]) >>> func() >>> n
I am not sure what problem you see/expect, but there is something for sure:
Mutable default arguments EDIT: >>> def func(n=[]): ... pass ... >>> func([1, 2, 3]) >>> func() >>> n Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'n' is not defined >>>Do you refer to NameError, i.e. why you get it?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link Create MCV example Debug small programs
As per my knowledge, I think the request for 'n' raises a NameError. This is since n is a variable local to func and we cannot access it elsewhere. It is also true that Python only evaluates default parameter values once; every invocation shares the default value. If one invocation modifies it, that is what another gets. This means you should only ever use primitives, strings, and as default parameters, not mutable objects.
|
|