sys.argv and while loop

Mark Hadfield m.hadfield at niwa.co.nz
Wed May 8 17:14:51 EDT 2002


"Julia Bell" <Julia.Bell at jpl.nasa.gov> wrote in message
news:3CD955A1.43AE9120 at jpl.nasa.gov...

> If I use string.atoi(variable) or string.atof(variable), but
> variable cannot be converted to an integer or float, I get an error.
> I'm just learning about catching exceptions, so I think I could
> figure out how to catch the error and do something appropriate if
> that's the recommended approach.  But, is there a better way
> (perform the test before trying to do the conversion)?

Probably not. The Pythonic way of seeing if something is going to work
is "try it and see" (and catch any exceptions). A Python guru (which I
am not) could explain why this is the recommended approach, but as I
understand it there are 2 reasons:

  - Exceptions are not expensive in Python.

  - If you are wondering whether some operation will work, it is very
  hard (especially in a dynamic language like Python) to anticipate
  all the conditions need to be satisfied. Trying the operation itself
  cuts to the heart of the matter.

One other comment: instead of string.atoi(value) you can use
int(value). It makes little difference in this case because the
elements of sys.argv are guaranteed to be strings, but in another
situation you want to allow the possibility that the value is
already an integer, or some other non-string type that can be
converted to an integer.

--
Mark Hadfield            "Ka puwaha et tai nei, Hoea tatou"
m.hadfield at niwa.co.nz
National Institute for Water and Atmospheric Research (NIWA)





More information about the Python-list mailing list