What's wrong with this code?

Andrew Cooper amc96 at cam.ac.uk
Tue Jul 24 03:19:29 CEST 2012


On 23/07/2012 15:50, Stone Li wrote:
> I'm totally confused by this code:
> 
> Code:
> 
>     a = None
>     b = None
>     c = None
>     d = None
>     x = [[a,b],
>          [c,d]]
>     e,f = x[1]
>     print e,f
>     c = 1
>     d = 2
>     print e,f
>     e = 1
>     f = 2
>     print c,d
> 
> Output:
> 
>     None None
>     None None
>     1 2
>      
> 
> 
> I'm expecting the code as:
> 
>     None None
>     1 2
>     1 2
>      
> 
> 
> What's wrong?
> And this question made my GUI program totally out of control.
> Thanks

c = 1 and d = 2 are overwriting the variable c (= None) and d (= None)
with new variables 1 and 2.  As x already captured c and d while they
were none, the variables e and f do not change (not would the, even if
you subsequently changed x)

Python is a statically scoped language, whereas the functionality you
are expecting would be an example of dynamically scoped.

Care to reveal your programming background?

~Andrew



More information about the Python-list mailing list