Simple Python question for some

Chris Rebert clp2 at rebertia.com
Sun Oct 28 20:18:48 EDT 2012


On Sun, Oct 28, 2012 at 4:51 PM, Mark L. Hotz <mlhotz at gmail.com> wrote:
> I have what I think should be a relatively simple question for someone who
> is knowledgeable about Python.
>
> At the IDLE prompt, when I enter “b” > 99, it responds True. In fact, it
> doesn’t matter which number is entered here, “b” is always greater (e.g. “b”
>> 1 == True; “b” > 100000 == True, or “b” < 99 = False).
>
> Why is this true?

Per http://docs.python.org/2/library/stdtypes.html#comparisons :
"Objects of different types, except different numeric types and
different string types, […] are ordered consistently but arbitrarily
(so that sorting a heterogeneous array yields a consistent result)."
Note that the "except" part just means that, e.g. floats and ints can
be compared with each other, and Unicode and byte strings can be
compared with each other. It does NOT mean that numbers and strings
can be meaningfully compared with each other.

This is fixed in Python 3, where such nonsensical comparisons will
instead raise TypeError.

>  If I use ord(“b”) it returns 98, so Python cannot be
> using the ASCII or Unicode value when interpreting “b” > 99.

It has nothing to do with implicit casting between strings and numbers
(which, as a general rule, Python does not do).

>From the same linked section as before:
"CPython implementation detail: Objects of [incompatible types] are
ordered by their type names"

So ints come before strs because "int" comes before "str" lexicographically.

Cheers,
Chris



More information about the Python-list mailing list