Easy(?) newbie question

Ron Stephens rdsteph at earthlink.net
Sun Nov 11 19:04:27 EST 2001


In other words, exec is a statement, but eval and execfile are functions. Since
eval is a function, it doesn't make sense to give it a for loop. Try using exec
instead, I think it will work like you expect.

Hye, I'm a newbie too, and this eval and exec stuff has always confused me. I hope
my adive above is correctly stated. ;-))))


Gerhard Häring wrote:

> On Sun, Nov 11, 2001 at 10:16:38PM +0000, Erik Johnson wrote:
> >
> > Hi,
> >
> >     I am just getting savvy to Python - rather excited about the
> > possibilities, but I have come across something that seems rather simple
> > but I'm stumped...
> >
> > The following loop does what I would expect:
> >
> > >>> for x in range(10): print x,
> > ...
> > 0 1 2 3 4 5 6 7 8 9
> >
> > but when I try to put this code into a string and evaluate it, I get a
> > syntax error:
> >
> > >>> s = "for x in range(10): print x,"
> > >>> s
> > 'for x in range(10): print x,'
> > >>> eval(s)
>
> eval() evaluates expressions, exec() executes statements. More about what is an
> expression/a statement can be found in the Python documentation.
>
> Also, the Python interactive prompt does both execute and evaluate, depending
> on what you feed it.
>
> Gerhard
> --
> mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
> web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
> public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
> reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))







More information about the Python-list mailing list