exec example - I don't understand
fowlertrainer at anonym.hu
fowlertrainer at anonym.hu
Tue Jun 29 09:18:51 EDT 2004
HI !
Thanx for every answer.
But it is a "bad" thing: when I think to I know something about python I
get some not understanded source code with helpful people's answers, and
them show me that I don't know nothing...
:-)
Christopher T King wrote:
>On Tue, 29 Jun 2004, kepes.krisztian at peto.hu wrote:
>
>
>
>>>>>print a # show the result
>>>>>
>>>>>
>>{1: 3.25, 2: 200}
>>
>>
>>>>>print a.keys()
>>>>>
>>>>>
>>[1, 2]
>>
>>
>>>>>exec "x = 3; print x" in a
>>>>>
>>>>>
>>3
>>
>>But I dont' understand that:
>> exec "x = 3; print x" in a
>>
>>So what this code do ?
>>Why we need "in a" ?
>>
>>
>
>The 'in a' tells exec to run the code using the dictionary a to read and
>store variables. In this case, when x is set equal to 3, it's actually
>a['x'] being set to 3. Try these examples to get an idea for what's going
>on:
>
>
>
>>>>a = {'x': 15}
>>>>exec 'print x' in a
>>>>
>>>>
> 15
>
>
>>>>exec 'print x'
>>>>
>>>>
> NameError: name 'x' is not defined
>
>
>>>>exec 'x*=3; print x' in a
>>>>
>>>>
> 45
>
>
>>>>x
>>>>
>>>>
> NameError: name 'x' is not defined
>
>
>>>>a['x']
>>>>
>>>>
> 45
>
>
>>>>exec 'y=10; print y' in a
>>>>
>>>>
> 10
>
>
>>>>y
>>>>
>>>>
> NameError: name 'y' is not defined
>
>
>>>>a['y']
>>>>
>>>>
> 10
>
>
>
>
More information about the Python-list
mailing list