Strange side effect from reading a list of numbers from argv
Neel Krishnaswami
neelk at brick.cswv.com
Sun Jul 18 19:12:30 EDT 1999
In article <O3sk3.6047$Sg6.52046 at news1.rdc1.sdca.home.com>,
Harold Gottschalk <heg at softbrew.com> wrote:
>I just wrote this program to become familiar with python and I do not
>understand why it works with a list I create with in the program and not
>when I use sys.argv[1:].
>
>I am sure there is some nuance I am missing, but an explanation to its
>behavior would be helpful.
The elements of sys.argv are *strings*, and strings compare
ascii-betically:
>>> "3" > "2"
1
>>> "3" > "20"
1
Just like "bat" > "ant", and "bat" > "anthropologist".
To convert elements of sys.argv (or any string) into numbers, use the
int() or float() built-in functions, depending on whether you want an
integer or floating-point number.
>>> int("3") > int("2")
1
>>> int("3") > int("20")
0
More like what you wanted, right?
It would be nice if the comparison between your number and the string
had raised an exception, but that's not how Python comparisons work --
the language reference documents this in Section 5.9:
The operators "<", ">", "==", ">=", "<=", and "!=" compare the values
of two objects. The objects needn't have the same type. If both are
numbers, they are coverted to a common type. Otherwise, objects of
different types always compare unequal, and are ordered consistently
but arbitrarily.
Nonetheless, this is IMHO a misfeature. We'll just have to live with
a language that's 95% perfect. :)
Neel
More information about the Python-list
mailing list