Beginnger Question

Sibylle Koczian Sibylle.Koczian at Bibliothek.Uni-Augsburg.de
Wed Apr 10 08:09:26 EDT 2002


>I'm a newbie myself, so this is probably wrong, but wouldn't this be *even*
>better?
>
>x = 2
>def wrong(num):
>    x = x+1
>    print x
>
>wrong(x)
>wrong(x)
>
>
Just tested with Python 2.2:

>>> x = 2
>>> def wrong(num):
...  x = x + 1
...  print x
...
>>> wrong(x)
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 2, in wrong
UnboundLocalError: local variable 'x' referenced before assignment

I think the exception is new (result of nested scopes?), but it's quite
probable you meant to write

x = 2
def wrong(num):
    num = num + 1
    print num

Result:

wrong(x)
3
wrong(x)
3

for the reason already stated: call by value, which works on a copy of the
parameter inside the function and doesn't change the parameter itself.
(Would be the same in C, by the way.)

So the "return num + 1" is really crucial, if you want your x to change.

HTH,
Koczian

--
Dr. Sibylle Koczian
Universitaetsbibliothek , Abt. Naturwiss.
D-86135 Augsburg
e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE






More information about the Python-list mailing list