Informatics Practices · Ch 3 — Brief Overview of Python
Relational Operators
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
| Operator | Operation | What it does |
|---|---|---|
== | Equals to | If the values of the two operands are equal, the condition is True; otherwise it is False |
!= | Not equal to | If the values of the two operands are not equal, the condition is True; otherwise it is False |
> | Greater than | If the value of the left operand is greater than the value of the right operand, the condition is True; otherwise it is False |
< | Less than | If 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
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. …
| Operator | Operation | Description | Example (Try in Lab) |
|---|---|---|---|
| == | Equals to | If values of two operands are equal, then the condition is True, otherwise it is False. | >>> num1 == num2False>> str1 == str2False |
| != | Not equal to | If values of two operands are not equal, then condition is True, otherwise it is False | >>> num1 != num2True>>> str1 != str2True>>> num1 != num3False |
| > | Greater than | If the value of the left operand is greater than the value of the right operand, then condition is True, otherwise it is False. | >>> num1 > num2True>>> str1 > str2True |