Lesson Contents
Python comparison operators are one of the operator types and allow us to compare two values and return a boolean result (True or False).
Let me show you some examples.
Equal
We can check if two items are equal. Here is an example where we compare two numbers:
>>> 1 == 1
Will show this output:
True
You can also compare two strings:
>>> "router" == "switch"
Will show this output:
False
Or other items, perhaps two lists:
>>> ["R1","R2"] == ["R3","R4"]
Will show this output:
False
Not Equal
This is the same logic as the equal operator, but the other way around. Let’s compare two numbers:
>>> 5 != 4
Will show this output:
True
Or compare two strings:
>>> "Firewall" != "Switch"
Will show this output:
True
Greater Than
The greater than operator checks if a number is greater than another number. For example:
>>> 3 > 2
Will show this output:
True
The number has to be greater than, if they are equal then the output is false:
>>> 2 > 2
Will show this output:
False
Less Than
The less than operator is the same as the greater than operator, but the other way around. For example:
>>> 10 < 11
Will show this output:
True
10 is less than 11 so this equals true. 10 is not less than 10 however:
>>> 10 < 10
Will show this output:
False
Greater than or equal to
We can also use the greater than or equal to operator. For example:
>>> 5 >= 4
Will show this output:
True
5 is greater than 4 so this equals true. Another example:
>>> 5 >= 5
Will show this output:
True
5 is equal to 5 so this is true. Last one:
>>> 5 >= 6
Will show this output:
False
5 is not greater than 6 so this is false.
Less than or equal to
Or we can use the less than or equal to operator. Example:
>>> 9 <= 10
Will show this output:
True
9 is less than 10 so this is true. 9 is equal to 9 so this is also true: