Home ยป Python Comparison Operators: A Tutorial

Python Comparison Operators: A Tutorial

Comparison operators in Python are used to compare two values and return a Boolean value (True or False) based on the condition.

These operators are essential in control flow structures such as if statements and loops.

In this tutorial, we will cover the different types of comparison operators, explain how they work, and provide examples.

1. Basic Comparison Operators in Python

Operator Description
== Equal: Returns True if both values are equal
!= Not equal: Returns True if values are not equal
> Greater than: Returns True if left operand is greater
< Less than: Returns True if left operand is smaller
>= Greater than or equal to: Returns True if left operand is greater than or equal to the right
<= Less than or equal to: Returns True if left operand is less than or equal to the right

 

2. Examples of Comparison Operators

a) Equal (==)

The == operator checks whether two values are equal. If they are, it returns True; otherwise, it returns False.

# Example of equal comparison
a = 10
b = 20

result = (a == b)
print(result)  # Output: False

result = (a == 10)
print(result)  # Output: True

b) Not Equal (!=)

The != operator checks whether two values are not equal. If they are not equal, it returns True; otherwise, it returns False.

# Example of not equal comparison
a = 10
b = 20

result = (a != b)
print(result)  # Output: True

result = (a != 10)
print(result)  # Output: False

c) Greater Than (>)

The > operator checks if the left operand is greater than the right operand. If it is, it returns True; otherwise, it returns False.

# Example of greater than comparison
a = 10
b = 5

result = (a > b)
print(result)  # Output: True

result = (a > 10)
print(result)  # Output: False

d) Less Than (<)

The < operator checks if the left operand is less than the right operand. If it is, it returns True; otherwise, it returns False.

# Example of less than comparison
a = 10
b = 20

result = (a < b)
print(result)  # Output: True

result = (a < 5)
print(result)  # Output: False

e) Greater Than or Equal to (>=)

The >= operator checks if the left operand is greater than or equal to the right operand. If it is, it returns True; otherwise, it returns False.

# Example of greater than or equal to comparison
a = 10
b = 10

result = (a >= b)
print(result)  # Output: True

result = (a >= 15)
print(result)  # Output: False

f) Less Than or Equal to (<=)

The <= operator checks if the left operand is less than or equal to the right operand. If it is, it returns True; otherwise, it returns False.

# Example of less than or equal to comparison
a = 10
b = 20

result = (a <= b)
print(result)  # Output: True

result = (a <= 5)
print(result)  # Output: False

3. Using Comparison Operators with Control Flow

Comparison operators are often used with conditional statements like if, elif, and else to control the flow of the program based on the results of comparisons.

Example: Check if a number is positive, negative, or zero

# Function to check if a number is positive, negative, or zero
def check_number(num):
    if num > 0:
        print(f"{num} is positive.")
    elif num < 0:
        print(f"{num} is negative.")
    else:
        print(f"{num} is zero.")

# Test cases
check_number(10)   # Output: 10 is positive.
check_number(-5)   # Output: -5 is negative.
check_number(0)    # Output: 0 is zero.

Example: Check if two numbers are equal

# Function to compare two numbers
def compare_numbers(a, b):
    if a == b:
        print(f"{a} and {b} are equal.")
    else:
        print(f"{a} and {b} are not equal.")

# Test cases
compare_numbers(10, 10)  # Output: 10 and 10 are equal.
compare_numbers(10, 20)  # Output: 10 and 20 are not equal.

4. Chaining Comparison Operators

Python allows you to chain comparison operators for more complex conditions, making your code more readable and concise.

Example: Check if a number is within a range

# Checking if a number is within a range (between 10 and 20)
num = 15

# Chaining comparison operators
if 10 <= num <= 20:
    print(f"{num} is between 10 and 20.")
else:
    print(f"{num} is not between 10 and 20.")

This is equivalent to:

# Equivalent without chaining
if num >= 10 and num <= 20:
    print(f"{num} is between 10 and 20.")
else:
    print(f"{num} is not between 10 and 20.")

5. Comparing Strings

Python allows you to compare strings based on lexicographical order (alphabetical order). The comparison is case-sensitive, meaning that uppercase and lowercase letters are considered different.

# Comparing strings
string1 = "apple"
string2 = "banana"

# Check if string1 is less than string2 (alphabetically)
print(string1 < string2)  # Output: True (since 'apple' comes before 'banana')

# Check if string1 is equal to string2
print(string1 == string2)  # Output: False

# Case-sensitive comparison
string3 = "Apple"
print(string1 == string3)  # Output: False (lowercase 'a' and uppercase 'A' are different)

6. Using Comparison Operators with Lists and Tuples

Python also allows comparison of lists and tuples based on lexicographical order (element-wise comparison).

Example: Compare lists

# Comparing lists
list1 = [1, 2, 3]
list2 = [1, 2, 4]

# Check if list1 is less than list2
print(list1 < list2)  # Output: True (because 3 is less than 4)

# Check if list1 is equal to list2
print(list1 == list2)  # Output: False

Example: Compare tuples

# Comparing tuples
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 3)

# Check if tuples are equal
print(tuple1 == tuple2)  # Output: True

# Check if one tuple is greater than another
tuple3 = (1, 2, 4)
print(tuple1 < tuple3)  # Output: True

7. Practical Examples

a) Age Validator

Let’s write a program that checks whether a user is eligible to vote based on their age.

def check_voting_eligibility(age):
    if age >= 18:
        print("You are eligible to vote.")
    else:
        print("You are not eligible to vote.")

# Test cases
check_voting_eligibility(20)  # Output: You are eligible to vote.
check_voting_eligibility(16)  # Output: You are not eligible to vote.

b) Max of Three Numbers

This program uses comparison operators to find the maximum of three numbers.

def max_of_three(a, b, c):
    if a >= b and a >= c:
        return a
    elif b >= a and b >= c:
        return b
    else:
        return c

# Test case
result = max_of_three(10, 20, 15)
print(f"The maximum value is: {result}")  # Output: The maximum value is: 20

Summary

==, !=, >, <, >=, <=: Basic comparison operators.
Chaining comparisons: You can chain operators for compact conditions.
Comparison of strings and sequences: Python compares lexicographically.
Comparison operators return Boolean values (True or False) and are frequently used in control flow and decision-making in Python programs.

By mastering comparison operators, you’ll be able to implement a wide variety of logic-driven tasks in your Python programs.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More