Chapter 2: Comparison operators

Comparison operators

face Josiah Wang

So far, I have introduced various operators in Python:

  • the assignment operator =
  • arithmetic operators +, -, *, /, //, %, **

Also recall that some operators can be repurposed depending on the type of the operand. For example, you can stick two strings together when you add them, or you can replicate a string when you multiply it by an integer.

Now, let us look at another set of operators. These are comparison operators. Recall that we have used some of these in our guessing game.

  • > (greater than)
  • < (less than)
  • == (equal to. Remember: two equal signs!)
  • != (\neq, not equal to)
  • >= (\ge, greater than or equal to)
  • <= (\le, less than or equal to)

Again, operands can be any object.

Question: what is the type of the object that results from such comparisons, for example 3 == 4?

Think about it for a minute…

Answer: all comparisons return either True or False (so the type is bool). So these are also known as boolean expressions.