Comparison Operators

We just learned about Boolean values (true or false). We can generate boolean values using comparison operators. Comparison operators compare two values and evaluate down to a single Boolean value.

Comparison Operators:

Operator Meaning
== Equals to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

The > operator is the traditional sign for is greater than, and the < is the traditional sign for is less than. The result of a comparison operator is a boolean value, stating whether the comparison is valid. These operators evaluate to True or False depending on the values you give them.

Lets explain with examples (use the console for it, i.e., the black box on the right side of your Repl screen):

>>> 2 == 4
False
>>> 2 != 4
True
>>> 2 < 4
True
>>> 2 > 4
False
>>> 2 <= 4
True
>>> 2 >= 4
False

As you might expect, == (equal to) evaluates to True when the values on both sides are the same, and != (not equal to) evaluates to True when the two values are different.

The == and != operators can work with values of any data type. Note that an integer or floating-point value will always be unequal to a string value. The expression 2 == '2' evaluates to False because Python considers the integer 2 to be different from the string '2'.

The <, >, <=, and >= operators, on the other hand, work well only with integer and floating-point values.

Difference between the = and == operators:

You might have observed that the == operator (equal to) has two equal signs, while the = operator (assignment) has just one equal sign. Students often get confused between these two operators. Here are three key points to not make this mistake:

  • The == operator (equal to) asks whether two values are the same as each other.

  • The = operator (assignment) puts the value on the right into the variable on the left.

  • To help remember which is which, notice that the == operator (equal to) consists of two characters, just like the != operator (not equal to) consists of two characters.

Example:

>>> data = 40
>>> data <= 40
True
>>> student = 15
>>> student == 15
True

You’ll often use comparison operators to compare a variable’s value to some other value, like in the data <= 40 and student == 15 examples. (After all, instead of typing 'dog' != 'cat' in your code, you could have just typed True.) You’ll see more examples of this later when you learn about flow control statements.

results matching ""

    No results matching ""