which a is used?

alex23 wuwei23 at gmail.com
Mon Sep 24 20:08:45 EDT 2012


On Sep 25, 9:43 am, Jayden <jayden.s... at gmail.com> wrote:
> Dear All,
>
> I have a simple code as follows:
>
> # 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?

Because you don't declare 'a' in 'f', it looks for 'a' in the
surrounding scope _where it was defined_, not where it was called.
Because 'a' in the module scope is 1, you'll get 1.



More information about the Python-list mailing list