Error Trapping In Python

Hans Nowak ivnowa at hvision.nl
Thu Jul 8 01:36:41 EDT 1999


On 7 Jul 99, Jonathon wrote:

> 
>  The script I am writing expects the user to input an
>  integer.   Being on the safe side, it reads the raw
>  data as a string.   However, to convert that string
>  to an integer, is perplexing me.
> 
>  string.atoi.(read_data) will give a value error if
>  read_data contains something other than a number.
> 
>  int ( read_data ) gives a Value Error, if non numerical
>  data is included.  <<  Or even if 10.0 is written instead
>  of 10  >>

You can trap such errors with exceptions... A simple example:

try:
    i = int(mystring)
except ValueError:
    print 'Cannot be converted'

There are others ways, of course. For instance, you could scan that 
string and filter out any unwanted characters (other than 0-9, 
probably). Or in the case of 10.0, you could try to convert to a 
float and if that succeeds, convert to an int, which causes any 
decimals to be chopped off.

--Hans Nowak (zephyrfalcon at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
Python Snippets: http://www.hvision.nl/~ivnowa/snippets/
The Purple Kookaburra Forum: http://www.delphi.com/kookaburra/




More information about the Python-list mailing list