sys.argv and while loop

Julia Bell Julia.Bell at jpl.nasa.gov
Wed May 8 12:43:13 EDT 2002


Thanks for all of the advice.  I'm converting from perl, so I'm not used to
thinking about the difference between a string and a number in general.

(We are planning to upgrade our version of python in the next few months.)

Now that I know I have to worry about type, what is the best way to determine
if a string is convertible to a number (integer or float)?

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)?

Julia Bell

Duncan Booth wrote:

> Julia Bell <Julia.Bell at jpl.nasa.gov> wrote in
> news:3CD9376E.BEF43213 at jpl.nasa.gov:
>
> > Using Python 1.3 on an HP (UNIX) (to write my first Python script):
> If you can get that upgraded to something a bit more recent you will be
> doing yourself a favour.
>
> > How can I define orbits to equal the value of the command line argument
> > and later use that variable to simply represent the number?
>
> The program arguments in sys.argv are all strings. You can compare a number
> with a string, but you won't get the result you expect. What you have to do
> is to convert the argument to an integer:
>
> #!/usr/local2/bin/python
> import sys
> count = 0
> orbits = int(sys.argv[1])
> while count < orbits:
>     print count, orbits
>     count = count + 1
>     if count > 100:    # use this to prevent the infinite loop
>         sys.exit ( 1 )
>
> A useful tip when weird things happen is to use the repr function when
> printing the values:
>
> >>> count = 1
> >>> orbits = '16'
> >>> print count, orbits
> 1 16
> >>> print repr(count), repr(orbits)
> 1 '16'
> >>>
> In this case the quotes would have shown that you were comparing a number
> to a string.
>
> --
> Duncan Booth                                             duncan at rcp.co.uk
> int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
> "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list