eval vs. atof

Gerrit Holl gerrit.holl at pobox.com
Wed Dec 22 05:59:47 EST 1999


Sposhua wrote:
> Newbie...
> 
> Why do string.ato[f/i/l] exist when you can use eval()? There must be a reason
> for these things...

If one evals something, the error is hard to trace:
>>> string.atoi("print")
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for atoi(): print
>>> eval("print")
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1
    print
       ^
SyntaxError: unexpected EOF while parsing

For example, if you want the user to type a valid number, you shouldn't
use input():
>>> input('type a number: ')
type a number: ['this', 'is', 'a', 'list!']
['this', 'is', 'a', 'list!']

You should use this instead:
>>> try:
...     num = string.atoi(raw_input("type a number: "))
... except ValueError:
...     print 'not a valid number'
...
type a number: 24
>>> try:
...     num = string.atoi(raw_input("type a number: "))
... except ValueError:
...     print 'not a valid number'
...
type a number: ['this', 'is', 'a', 'list]
not a valid number

regards,
Gerrit.
-- 
"Open Standards, Open Documents, and Open Source"

  -- Scott Bradner (Open Sources, 1999 O'Reilly and Associates)
 11:56am  up 51 min, 16 users,  load average: 0.00, 0.01, 0.01




More information about the Python-list mailing list