exec example - I don't understand

Christopher T King squirrel at WPI.EDU
Tue Jun 29 09:09:31 EDT 2004


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