In my python CS class at school, we were given a true or false question as follows.

A comparison function returns either True or False.

When originally answering I thought about two things. First, a function as follows (what I thought was a comparison function) returns true or false.

def comparison(valOne,valTwo):
    return valOne<valTwo

Now, I know this isn't a comparison function, but a function with an operator. In addition, I thought of another type of function when answering.

def someoneHasOne(scoreOne,scoreTwo):
    return scoreOne==15 or scoreTwo==15

From what I know, this is a comparison function.

So, thinking of those two things, I marked this as True.

However, the correct answer, according to the teacher, was False. After the answer was marked wrong, I started to do some research. I found this about the operator module that has comparison functions that return True or False

My main question is, am I right (the answer is True)? Or is my CS teacher right (the answer is False)?

  • 2
    Depends what you mean by "comparison function". Sometimes you want a three-way comparison so that you can handle "less than", "equal to", and "greater than" separately, rather than e.g. just "less than" and "not less than". In some languages (PHP among them), you use the spaceship operator <=> for this. In Python 2, the cmp function does the same thing. For a three-way comparison, True/False clearly doesn't suffice. More common is to return -1, 0, 1. In languages with good sum types like Haskell, you're more likely to see something like LT | EQ | GT. – senshin Dec 10 '15 at 1:03
  • For other languages to see how this works - strcmp for C, <=> and cmp for perl, compareTo from Comparable or the Comparator in Java, IComparable.CompareTo and Comparison<T> in C#, the Ordered trait with compare in scala, (compare x y) in Scala... – user40980 Dec 10 '15 at 2:12

If this is a python class, then yes, your CS teacher is correct. A number of python functions take a "comparison function" as an argument. For instance, see the sorted documentation:

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

How comparison functions work varies by language, though most follow a similar fashion. But since this is specifically a question about python, the answer is unambiguously "false" in that comparison functions do not always return just True or False.

  • alternatively this is called something different in other languages e.g. java 8 would call this a BiPredicate – jk. Dec 10 '15 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.