which a is used?

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Tue Sep 25 05:30:54 EDT 2012


Jayden <jayden.shui at gmail.com> 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.



More information about the Python-list mailing list