[Tutor] cmp()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 14 Aug 2002 15:28:20 -0700 (PDT)


On Wed, 14 Aug 2002, Kyle Babich wrote:

> I was just reading the UselessPython tutorial with the cmp() program.
> I haven't learned cmp() yet so while I was reading it I thought I would
> launch IDLE and try it out, but I can't make sense of it.
>
> >>> cmp(937, 22)
> 1
> >>> cmp("abc", "abc")
> 0
> >>> cmp("abc", "def")
> -1
>
> Why does it say 937 and 22 are equal?  Why does it say abc and abc
> aren't equal?  Why does it say -1 for abc and def, shouldn't it say 0?
> How do I make sense of this?

Hi Kyle:

The quick answer is that cmp() isn't meant to be a "boolean" function:
it is not meant to say "yes" or "no".  Instead, it gives 3 particular
values:

    cmp(x,y) = 0                      if x == y
               some positive value    if x > y
               some negative value    if x < y

cmp() just does more than you expect, so don't worry too much.  Everyone
gets caught by this at least once, because we're all so used to seeing
boolean functions.


Hope this helps!