[Tutor] strange eval
Doug Penny
doug.penny at gmail.com
Tue Oct 5 15:00:54 CEST 2004
Thanks for the info. Good point about using eval(). They have been
shown int(), but for some reason this student started using eval() and
I just didn't think about guiding him back to int().
Doug
On Mon, 4 Oct 2004 07:05:59 -0700 (PDT), Danny Yoo
<dyoo at hkn.eecs.berkeley.edu> wrote:
>
> 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')
> 10
> >>> int('0100')
> 100
> ###
>
> If we really want an octal interpretation, we can explicitely tell int()
> what base to use:
>
> ###
> >>> int('010', 8)
> 8
> >>> int('0100', 8)
> 64
> ###
>
> 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
> like.
>
> Hope this helps!
>
>
More information about the Tutor
mailing list