Comparison Operators
Part of the Fundamentals section of Coddy's Python journey — lesson 14 of 77.
Comparison operators are used to compare between two operands.
Sometimes we need to check whether an operand is greater than, less than, or equal to another operand. The following table shows possible operators for comparison:
| Operator | Meaning | Example |
|---|---|---|
| == | Equal | 1 == 2 returns false |
| != | Not Equal | 1 != 2 returns true |
| > | Greater Than | 1 > 2 returns false |
| < | Less Than | 1 < 2 returns true |
| >= | Greater Than or Equal | 1 >= 2 returns false |
| <= | Less Than or Equal | 1 <= 2 returns true |
The comparison operator returns True if the comparison is true and False otherwise.
For example:
var1 = 13
var2 = 12
var3 = var1 != var2var3 will hold True because var1 and var2 are not equal
Another example:
var1 = 13
var2 = 13
var3 = var1 == var2var3 will hold True because var1 and var2 are equal
Remember the
booleantype,var3is a boolean.
Challenge
BeginnerWrite a script that initializes 2 variables n1 and n2 with the values 8 and 9 (accordingly).
After that initialize another variable n3 that will hold whether n1 is bigger than n2.
Cheat sheet
Comparison operators in Python:
| Operator | Meaning | Example |
|---|---|---|
| == | Equal | 1 == 2 returns False |
| != | Not Equal | 1 != 2 returns True |
| > | Greater Than | 1 > 2 returns False |
| < | Less Than | 1 < 2 returns True |
| >= | Greater Than or Equal | 1 >= 2 returns False |
| <= | Less Than or Equal | 1 <= 2 returns True |
Comparison operators return True or False (boolean values).
Example 1:
var1 = 13
var2 = 12
var3 = var1 != var2 # var3 will be TrueExample 2:
var1 = 13
var2 = 13
var3 = var1 == var2 # var3 will be TrueTry it yourself
# Type your code below
# Don't change the line below
print(f"n1 = {n1}, n2 = {n2}, n3 = {n3}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2