[Tutor] eval and exec

Brian van den Broek bvande at po-box.mcgill.ca
Sat Dec 4 10:51:33 CET 2004


Brian van den Broek said unto the world upon 2004-12-04 04:28:
> Marilyn Davis said unto the world upon 2004-12-04 01:37:
> 
>> Hello Tutors,
>>
>> I'm having trouble understanding the difference between eval and exec.
>>
>> Can anyone explain it to me please?
>>
>> Marilyn Davis
>>
> 
> Hi Marilyn,
> 
> does this help?

<SNIP>

Darn. I left a few things that might help:

>>> exec("a = 2 + 40")
>>> exec("print a")
> 
> 42
> 
 >>> eval('a')
42
 >>>

As before, exec("a = 2 + 40") runs the code "a = 2 + 40", making 'a' 
point to 42.
Thus, exec("print a") is synonymous with:
 >>> print a

*in the interpreter* "eval('a')" also gives 42. This is because, *in the 
interpreter*
 >>> a
42

But, run this script:

exec('a=42')
exec('print a')
exec("print eval('a') == eval('21 * 2')")
eval('a')
a

OUTPUT:
 >>> =========================== RESTART ===========================
 >>>
42
True
 >>>

*In a script*,
a
doesn't produce any output at all. This script does print 'True' because 
of the third line. It reads:

Run the sting "print eval('a') == eval('21 * 2')" as code.

So, print the expression you get by putting an '==' between the results 
of evaluating the expressions "a" and "21 * 2". Thus, print an 
expression equivalent to
42 == 42.

And its almost 5am and I've begun to worry I'm muddying the waters, 
rather than helping. It is to be hoped that someone will clean up any 
messes I have made. (Ken? Danny? . . . .)

Best,

brian vdB



More information about the Tutor mailing list