Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Relational Operators

3.6.2

Relational Operators

Arithmetic operators produce a new value; relational operators produce a verdict. A relational operator compares the values of the operands on its two sides and determines the relationship between them — are they equal? is one greater? The result of such a comparison is always either True or False, which is what makes relational operators the foundation of every decision a program takes.

To see them in action, keep these variables in mind — all the examples below use them:

num1 = 10
num2 = 0
num3 = 10
str1 = "Good"
str2 = "Afternoon"

The relational operators

OperatorOperationWhat it does
==Equals toIf the values of the two operands are equal, the condition is True; otherwise it is False
!=Not equal toIf the values of the two operands are not equal, the condition is True; otherwise it is False
>Greater thanIf the value of the left operand is greater than the value of the right operand, the condition is True; otherwise it is False
<Less thanIf the value of the left operand is less than the value of the right operand, the condition is True; otherwise it is False

Watching each operator work

Equals to (==). num1 holds 10 and num2 holds 0, so they are not equal; str1 ("Good") and str2 ("Afternoon") are different strings:

>>> num1 == num2
False
>>> str1 == str2
False

Not equal to (!=). This is the mirror image of == — it is True exactly when the values differ. Note the third example: num1 and num3 both hold 10, so "not equal" is False:

>>> num1 != num2
True
>>> str1 != str2
True
>>> num1 != num3
False

Greater than (>). For numbers this is the familiar comparison: 10 is greater than 0. For strings, the comparison is made in dictionary order using ASCII values — the first characters are compared, and only if they match does Python move to the next character. "Good" is greater than "Afternoon" because 'G' comes after 'A':

>>> num1 > num2
True
>>> str1 > str2
True

Less than (<). num1 and num3 both hold 10, so num1 is not less than num3:

>>> num1 < num3
False
Watch out

Do not confuse == (a relational operator that asks "are these equal?") with = (the assignment operator that stores a value in a variable). Writing num1 = num2 changes num1; writing num1 == num2 merely reports True or False and changes nothing. …

Table 3.4Relational operators in Python
OperatorOperationDescriptionExample (Try in Lab)
==Equals toIf values of two operands are equal, then the condition is True, otherwise it is False.>>> num1 == num2
False
>> str1 == str2
False
!=Not equal toIf values of two operands are not equal, then condition is True, otherwise it is False>>> num1 != num2
True
>>> str1 != str2
True
>>> num1 != num3
False
>Greater thanIf the value of the left operand is greater than the value of the right operand, then condition is True, otherwise it is False.>>> num1 > num2
True
>>> str1 > str2
True