initialization in argument definitions

Egon Frerich egon.frerich at nord-com.net
Fri Nov 21 18:00:50 EST 2008


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Brentt schrieb:
| Hi, I know this is a terribly simple question, but the docs seem to be
| designed for people who probably find a the answer to this question
| terribly obvious. But its not at all obvious to me.
|
| I can't figure out why when I define a function, a variable
| (specifically a list) that I define and initialize in the argument
| definitions, will not initialize itself every time its called. So for
| example, when making a simple list of a counting sequence from num (a
| range list), if I call the function multiple times, it appends the
| elements to the list generated the times it was called before, even
| though the variable for the list is initialized in the argument
| definitions.
|
| def foo_range(num,aList = []):
| aList = []
| #why is this seemingly extra initialization necessary? shouldn't it be
| initialized in the argument definitions?
| #but if its not there and the function is called multiple times the
| elements generated (see below)
| #append to the list generated before.
| while num <= 10:
| aList.append(num)
| num +=1
| else:
| return aList
|
| Why is this? Thanks, hope its not a stupid quesiton.



look up
http://docs.python.org/tutorial/controlflow.html#defining-functions

"The execution of a function introduces a new symbol table used for
the local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the local symbol tables of enclosing functions, then in the global
symbol table, and finally in the table of built-in names. Thus, global
variables cannot be directly assigned a value within a function (unless
named in a global statement), although they may be referenced."

Egon

| --
| http://mail.python.org/mailman/listinfo/python-list

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJJz2iZRiDo9Iq4qIRAhTLAJ41TTysvN++TNF1tvanjAxBPhdBawCfe1tY
uDdbPYWBAEkbYNhbKQGkx88=
=9gL8
-----END PGP SIGNATURE-----



More information about the Python-list mailing list