Comparison Operators in Python (original) (raw)

Comparison operators (or Relational) in Python allow you to compare two values and return a Boolean result: either True or False. Python supports comparison across different data types, such as numbers, strings and booleans. For strings, the comparison is based on lexicographic (alphabetical) order.

Now let’s look at all the comparison operators one by one.

1. Equality Operator (==)

The equality operator checks if two values are exactly the same.

**Example: In this code, we compare integers using the equality operator.

Python `

a = 9 b = 5 c = 9

print(a == b) print(a == c)

`

**Explanation: a == b is False because 9 is not equal to 5 and a == c is True because both values are 9.

**Note: Be cautious when comparing floating-point numbers due to precision issues. It’s often better to use a tolerance value instead of strict equality.

2. Inequality Operator (!=)

The inequality operator checks if two values are not equal.

**Example: Here, we check whether the numbers are different using !=.

Python `

a = 9 b = 5 c = 9

print(a != b) print(a != c)

`

**Explanation: a != b is True because 9 and 5 are different and a != c is False because both are 9.

3. Greater Than Operator (>)

Checks if the left operand is larger than the right.

**Example: Comparing two numbers with the greater-than operator.

Python `

a = 9 b = 5

print(a > b) print(b > a)

`

4. Less Than Operator (<)

Checks if the left operand is smaller than the right.

**Example: Comparing two numbers with the less-than operator.

Python `

a = 9 b = 5

print(a < b) print(b < a)

`

5. Greater Than or Equal To Operator (>=)

Checks if the left operand is greater than or equal to the right.

**Example: Using >= to check greater than or equal conditions.

Python `

a = 9 b = 5 c = 9

print(a >= b) print(a >= c) print(b >= a)

`

6. Less Than or Equal To Operator (<=)

Checks if the left operand is less than or equal to the right.

**Example: Using <= to check less than or equal conditions.

Python `

a = 9 b = 5 c = 9

print(a <= b) print(a <= c) print(b <= a)

`

7. Chaining Comparison Operators

Python allows you to chain multiple comparisons in a single statement. This makes conditions more compact and readable.

**Example: Using chained operators to evaluate multiple conditions together.

Python `

a = 5

print(1 < a < 10) print(10 > a <= 9) print(5 != a > 4) print(a < 10 < a*10 == 50)

`