[Tutor] eval and exec

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


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?

>>> print a

Traceback (most recent call last):
   File "<pyshell#13>", line 1, in -toplevel-
     print a
NameError: name 'a' is not defined
>>> # as expected, since 'a' doesn't yet point to anything.
>>> exec("a = 2 + 40")
>>> # this means 'Run the string "a = 2 + 40" by assuming it is Python
>>> # code. Python code instructions are called "statements". (See [*]
>>> # note below.
>>> exec("print a")
42
>>> # As before, run "print a" as code. Since we have run the code in
>>> # the string "a = 2 + 40" this is the expected result.
>>> eval("print a")

Traceback (most recent call last):
   File "<pyshell#16>", line 1, in -toplevel-
     eval("print a")
   File "<string>", line 1
     print a
         ^
SyntaxError: invalid syntax
>>> # Error because eval("print a") means 'take the expression[*]
>>> # in the string "print a" and evaluate it (tell me what it points
>>> # to). [*] "Expression" means *roughly* "name of some object". Since
>>> # 'print a' isn't an object at all but an instruction, eval
>>> # complains. (Do watch for more experienced posters to clarify on
>>> # the exact meaning of "expression" and "statement". I'm no expert.
>>> eval("a = 38 + 4")

Traceback (most recent call last):
   File "<pyshell#17>", line 1, in -toplevel-
     eval("a = 38 + 4")
   File "<string>", line 1
     a = 38 + 4
       ^
SyntaxError: invalid syntax
>>> # Again, an error, as "a = 38 + 4" is a statement (a code
>>> # instruction) and eval wants an expression.
>>> eval("a == 38 + 4")
True
>>> # As expected, as "a == 38 + 4" is a string for a complicated name of
>>> # True.

So, eval evaluates expressions (namelike things) and exec runs strings
as though they were Python code.

HTH,

Brian vdB



More information about the Tutor mailing list