[Tutor] strange eval

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Oct 4 16:05:59 CEST 2004

On Mon, 4 Oct 2004, Kent Johnson wrote:

> Number literals starting with 0 are interpreted as _octal_! See
> http://docs.python.org/ref/integers.html
>  >>> eval('010')
> 8
>  >>> eval('0100')
> 64
> 8 and 9 are not valid octal digits, hence the error.

Hi Doug,

And don't use eval() to get numbers from strings: it's far too powerful a
tool to be used casually!  *grin*

Use int() instead: it's a converter to integers:

>>> int('010')
>>> int('0100')

If we really want an octal interpretation, we can explicitely tell int()
what base to use:

>>> int('010', 8)
>>> int('0100', 8)

I also think it's not a good thing to teach students to use eval()
without showing the repercussions.  eval() has the same access to the
Python runtime as the running program, and that's dangerous if not handled
properly.  We can talk about the security implications of eval() if you'd

Hope this helps!

More information about the Tutor mailing list