Jayden <[email protected]> writes:
> # Begin
> a = 1
>
> def f():
> print a
>
> def g():
> a = 20
> f()
>
> g()
> #End
>
> I think the results should be 20, but it is 1. Would you please tell me why?
When python looks at g(), it sees that a variable a is assigned to, and
decides it is a local variable. When it looks at f(), it sees a use of a
but no assignment, so it decides it is a global variable and fetches the
value from the outer scope.
If you change f() to:
def f():
print a
a = 30
you change a into a local variable (and get another error).
If you want to change the binding of a in g(), you can declare it
global:
def g():
global a
a = 20
f()
Very tricky, actually.
-- Alain.
--
http://mail.python.org/mailman/listinfo/python-list