2 3 2 Comparison Operators Explained
Key Concepts
Comparison operators in Python are used to compare two values. The 2 3 2 pattern refers to the use of two types of equality operators and three types of relational operators, which are essential for making decisions in programming.
1. Equality Operators
Equality operators check if two values are equal or not equal. There are two types of equality operators:
==
(Equal to)!=
(Not equal to)
1.1 Equal to (==
)
The ==
operator checks if two values are equal. It returns True
if the values are equal and False
otherwise.
x = 5 y = 5 result = x == y print(result) # Output: True
1.2 Not equal to (!=
)
The !=
operator checks if two values are not equal. It returns True
if the values are not equal and False
if they are equal.
a = 10 b = 20 result = a != b print(result) # Output: True
2. Relational Operators
Relational operators compare two values based on their magnitude. There are three types of relational operators:
>
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)
2.1 Greater than (>
)
The >
operator checks if the left value is greater than the right value. It returns True
if the condition is met and False
otherwise.
x = 15 y = 10 result = x > y print(result) # Output: True
2.2 Less than (<
)
The <
operator checks if the left value is less than the right value. It returns True
if the condition is met and False
otherwise.
a = 7 b = 14 result = a < b print(result) # Output: True
2.3 Greater than or equal to (>=
)
The >=
operator checks if the left value is greater than or equal to the right value. It returns True
if the condition is met and False
otherwise.
x = 20 y = 20 result = x >= y print(result) # Output: True
2.4 Less than or equal to (<=
)
The <=
operator checks if the left value is less than or equal to the right value. It returns True
if the condition is met and False
otherwise.
a = 30 b = 40 result = a <= b print(result) # Output: True
3. Practical Example: Using Comparison Operators in Conditional Statements
Comparison operators are often used in conditional statements to make decisions based on the comparison results. For example:
age = 18 if age >= 18: print("You are eligible to vote.") else: print("You are not eligible to vote.")
In this example, the >=
operator is used to check if the age is greater than or equal to 18, and the appropriate message is printed based on the result.