2

Possible Duplicate:
How does Python compare string and int?

I came across a weird comparison in Python today. Here's what I found:

'101' > -1
True

'101' < -1
False

'101' > 100
True

'101' < 100
False

'101' < 1
False

I'm not sure what these expressions are testing. Any hints would be helpful.

Community
  • 1
  • 1
Utkarsh Sinha
  • 3,295
  • 4
  • 30
  • 46

3 Answers3

2

From the language reference:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • 2
    You might want to point out that this goes away in python 3.x (in favor of a more logical `TypeError`) – mgilson Aug 30 '12 at 12:00
0

When you order a numeric and a non-numeric type, the numeric type comes first.

zenpoy
  • 19,490
  • 9
  • 60
  • 87
0

When you compare numeric and non-numeric types together, the numeric type must come first in order for the expression to be true, no matter what the value of either of the variables is.

When you compare two incompatible types in python it compares the names of the type alphabetically. See this question for more info.

I don't know why this expression would need to be tested ever. Prehaps they may be used to check the type e.g.

if foo < bar is true and bar is known not to be a numeric variable then foo must be a numeric value and can be used in calculations etc.

Community
  • 1
  • 1
Zigfreed
  • 1
  • 3