Python Forum
Is there an error in the code?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there an error in the code?
#1
I cannot find the problem with the following piece of code-
>>> def func(n=[]):
               #playing around
                pass
>>> func([1,2,3])
>>> func()
>>> n
Reply
#2
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

Reply
#3
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020