sys.argv and while loop

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed May 8 11:27:11 EDT 2002


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