Python Comparison Operators
Comparison Operators in Python
Comparison operators in Python are used to compare two values or variables. The result of a comparison is either True
or False
, depending on the condition. These operators are commonly used in conditional statements to make decisions based on the comparison of values.
List of Comparison Operators
Operator | Name | Description | Example | Output |
---|---|---|---|---|
== | Equal to | Returns True if both values are equal | a == b | False |
!= | Not equal to | Returns True if both values are not equal | a != b | True |
> | Greater than | Returns True if the first value is greater | a > b | False |
< | Less than | Returns True if the first value is smaller | a < b | True |
>= | Greater than or equal to | Returns True if the first value is greater or equal | a >= b | False |
<= | Less than or equal to | Returns True if the first value is smaller or equal | a <= b | True |
Examples of Comparison Operators
1. Equal to (==
)
The ==
operator checks whether two values are equal.
2. Not equal to (!=
)
The !=
operator checks whether two values are not equal.
3. Greater than (>
)
The >
operator checks whether the first value is greater than the second.
4. Less than (<
)
The <
operator checks whether the first value is less than the second.
5. Greater than or equal to (>=
)
The >=
operator checks whether the first value is greater than or equal to the second.
6. Less than or equal to (<=
)
The <=
operator checks whether the first value is less than or equal to the second.
Example with Conditional Statements
Comparison operators are commonly used in conditional statements (like if
statements) to control the flow of a program based on comparisons.
Example with Multiple Comparisons
You can use comparison operators in conjunction with logical operators to check multiple conditions.
Summary of Comparison Operators:
==
: Checks if two values are equal.!=
: Checks if two values are not equal.>
: Checks if the left value is greater than the right.<
: Checks if the left value is smaller than the right.>=
: Checks if the left value is greater than or equal to the right.<=
: Checks if the left value is smaller than or equal to the right.
Comparison operators are essential for making decisions and controlling the logic in Python programs.