Question 5.19: Comparing Values You want to compare values with each other....

Comparing Values

You want to compare values with each other.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use one of the comparison operators: <, >, <=], >=, ==, or !=.

Discussion

You use the < (less than) and > (greater than) operators in Recipe 6.15. Here’s the full set of comparison operators:

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

==

Exactly equal to

!=

Not equal to

Some people prefer to use the <> operator in place of !=. Both work the same.

You can test out these commands using the Python console (Recipe 5.3), as shown in the following exchange:

>>> 1 != 2
True
>>> 1 != 1
False
>>> 10 >= 10
True
>>> 10 >= 11
False
>>> 10 == 10
True
>>>

A common mistake is to use = (set a value) instead of == (double equals) in comparisons. This can be difficult to spot because if one half of the comparison is a variable, it is perfectly legal syntax and will run, but it will not produce the result you were expecting.

As well as comparing numbers, you can also compare strings using these comparison operators, for example:

>>> ‘aa’ < ‘ab’
True
>>> ‘aaa’ < ‘aa’
False

The strings are compared lexicographically—that is, in the order that you would find them in a dictionary.

This is not quite correct as, for each letter, the uppercase version of the letter is considered less than the lowercase equivalent.

See Also

See also Recipe 6.15.

Related Answered Questions

Question: 5.24

Verified Answer:

Create a function that groups together lines of co...
Question: 5.23

Verified Answer:

Use the Python break statement to exit either a wh...
Question: 5.22

Verified Answer:

Use the Python while statement. The while statemen...
Question: 5.21

Verified Answer:

Use the Python for command and iterate over a rang...
Question: 5.20

Verified Answer:

Use one of the logical operators: and, or, and not...
Question: 5.17

Verified Answer:

Use the upper or lower function as appropriate. Fo...
Question: 5.18

Verified Answer:

Use the Python if command. The following example w...
Question: 5.15

Verified Answer:

Use the Python [:] notation. For example, to cut o...
Question: 5.14

Verified Answer:

Use the find Python function. For example, to find...