sys.argv and while loop

Emanuel Borges eaborges at hotmail.com
Wed May 8 13:39:28 EDT 2002


Python 1.3....  Yiech!

Anyway, your script isn't working because the parameter you're passing
to it is coming in as a string and not an integer.  You said that when
you set orbits to 16 in the code it works.  That's because you're
setting it to an integer.  When you do  orbits = 16  it DOES work but
instead try  orbits = "16"  and you will notice the same bug.

So at some point in your code you will need to change orbits from a
string to an integer.  Like so...

import sys, string
count = 0
orbits = sys.argv[1]
orbits = string.atoi(orbits)
while count < orbits:
    print count, orbits
    count = count + 1
    if count > 100:    # use this to prevent the infinite loop it gets
        sys.exit ( 1 )

This should give you the result you're looking for...   I didn't just
do someone's homework, did I???

Emanuel Borges


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
> 
> The while loop does not exit when count becomes > 16 (until it hits the
> "if" statement that I included to prevent the infinite loop).
> If I replace the "orbits = sys.argv[1]" statement with "orbits = 16" and
> run the script without the argument (but still importing sys), the while
> loop does exit.
> 
> How can I define orbits to equal the value of the command line argument
> and later use that variable to simply represent the number?
> 
> Julia Bell



More information about the Python-list mailing list