Comparison Operators in Python
Python Comparison Operators
Python comparison operators are important tools for comparing values in your code. They allow you to evaluate conditions, make decisions, and control the flow of your programs. This lesson will cover the main comparison operators in Python: equal, not equal, greater than, less than, greater than or equal to, and less than or equal to. We will provide clear examples and practical use cases to help you understand how to use these operators effectively.
1. Equal (==)
The equal operator checks if two values are the same. If they are equal, it returns True
; if not, it returns False
.
Syntax:
python
1x == y
Example:
python
1a = 5
2b = 5
3result = a == b # result will be True
Practical Use:
Use the equal operator when you want to check if two variables hold the same value. This is useful in conditional statements to execute specific code when conditions are met.
2. Not Equal (!=)
The not equal operator checks if two values are different. It returns True
if the values are not equal and False
if they are.
Syntax:
python
1x != y
Example:
python
1a = 5
2b = 3
3result = a != b # result will be True
Practical Use:
Use this operator to ensure values are distinct, such as validating user input or checking conditions in your programs.
3. Greater Than (>)
The greater than operator checks if the left value is larger than the right value. It returns True
if the left value is greater; otherwise, it returns False
.
Syntax:
python
1x > y
Example:
python
1a = 10
2b = 5
3result = a > b # result will be True
Practical Use:
Use the greater than operator to compare numeric values, which is especially helpful in sorting or filtering data.
4. Less Than (<)
The less than operator checks if the left value is smaller than the right value. It returns True
if the left value is less; otherwise, it returns False
.
Syntax:
python
1x < y
Example:
python
1a = 3
2b = 5
3result = a < b # result will be True
Practical Use:
This operator is useful for evaluating conditions where you need to check if one value is less than another.
5. Greater Than or Equal To (>=)
The greater than or equal to operator checks if the left value is greater than or equal to the right value. It returns True
if the condition holds; otherwise, it returns False
.
Syntax:
python
1x >= y
Example:
python
1a = 5
2b = 5
3result = a >= b # result will be True
Practical Use:
Use this operator when you need to ensure a value meets a minimum requirement, such as age checks or score thresholds.
6. Less Than or Equal To (<=)
The less than or equal to operator checks if the left value is less than or equal to the right value. It returns True
if the condition is true; otherwise, it returns False
.
Syntax:
python
1x <= y
Example:
python
1a = 3
2b = 5
3result = a <= b # result will be True
Practical Use:
This operator is helpful for setting limits and validating conditions in your programs.