sys.argv and while loop

Brian McErlean b_mcerlean at yahoo.com
Wed May 8 13:00:06 EDT 2002


Julia Bell <Julia.Bell at jpl.nasa.gov> wrote in message news:<3CD9376E.BEF43213 at jpl.nasa.gov>...
> Using Python 1.3 on an HP (UNIX) (to write my first Python script):
> 
> In the following script, the while loop doesn't exit as expected if one
> of the variables in the conditional is assigned to equal sys.argv[1].
> It works as expected if I explicitly set the variable to the number
> (that is entered as the argument).
> 
> (stored in executable myscript.py)
> #!/usr/local2/bin/python
> import sys
> count = 0
> orbits = sys.argv[1]
> while count < orbits:
>     print count, orbits
>     count = count + 1
>     if count > 100:    # use this to prevent the infinite loop it gets
> into
>         sys.exit ( 1 )
> 
> The command line I use is:
> myscript.py 16

Note that the arguments to the script get passed as strings, so 
orbits = sys.argv[1] is actually equivalent to:
orbits = '16'

Python does not perform coercion of strings to numbers, but does define
an arbitrary order when comparing different types, hence "count < '16'" is
true for any number, so your loop never terminates.

What you really want is:

orbits = int(sys.argv[1])

Hope this helps,
Brian.



More information about the Python-list mailing list