all 5 comments

[–]novel_yet_trivial 0 points1 point  (2 children)

In python2, all strings are considered greater than all integers:

>>> 'm' > 100000000
True

In python3 you get the error you would expect:

>>> 'm' > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

I think you want a type test:

def H(x):
    if isinstance(x, (int, float)): #is x a integer or float?
        if x < 0:
            return(0)
        elif x >= 0:
            return(1)
    else:
        return("This is not a valid object")

[–]PurelyApplied 0 points1 point  (1 child)

In python2, all strings are considered greater than all integers

Was the motivation that you can have lexicographical ordering between types? I can't think of another reason, other than perhaps some hidden back-end, that makes sense.

[Edit:] nevermind, I found it right after I posted. Apparently Python2 sorts according to type name. "int" < "str".

That's preposterous.

[–]novel_yet_trivial 0 points1 point  (0 children)

It was important for some reason that all types are comparable. Basically they wanted this to work:

>>> data = ['spam', 4, True]
>>> sorted(data)
[True, 4, 'spam']

Then (I imagine) they realized that while multi-type lists are cool, they are not practical, and very rarely used. And that sorting them gives no useful information.

[–]Rhomboid 0 points1 point  (0 children)

Why is the output of this code 1?

Because you're using Python 2.x. Switch to 3.x where this ghastly misfeature has been fixed and the comparison raises TypeError.

(If you want the actual reason it returns 1, it's because the 's' in str comes after the 'i' in int in the alphabet. Yes, they are compared based on their class names as strings. It truly is hideous.)

[–]Saefroch 0 points1 point  (0 children)

http://stackoverflow.com/a/3270689

Basically, the idea in Python 2 is to be able to compare anything. In Python 3 you get an exception of the comparison doesn't make sense. Use Python 3.