Python Comparison Operators

Introduction

Comparison operators in Python are used to compare two values. These operators return a Boolean value (True or False) based on the comparison result. Understanding comparison operators is crucial for making decisions in your code, such as in conditional statements and loops.

List of Comparison Operators

Here is a list of the comparison operators available in Python, along with their descriptions and examples:

1. Equal to (==)

Checks if the values of two operands are equal.

Example:

x = 10
y = 10
print(x == y)  # Output: True

2. Not equal to (!=)

Checks if the values of two operands are not equal.

Example:

x = 10
y = 5
print(x != y)  # Output: True

3. Greater than (>)

Checks if the value of the left operand is greater than the value of the right operand.

Example:

x = 10
y = 5
print(x > y)  # Output: True

4. Less than (<)

Checks if the value of the left operand is less than the value of the right operand.

Example:

x = 10
y = 15
print(x < y)  # Output: True

5. Greater than or equal to (>=)

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

Example:

x = 10
y = 10
print(x >= y)  # Output: True

6. Less than or equal to (<=)

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

Example:

x = 10
y = 15
print(x <= y)  # Output: True

Examples of Using Comparison Operators

Here are some more examples demonstrating the use of comparison operators in Python:

# Example 1: Equal to
a = 5
b = 5
print(a == b)  # Output: True

# Example 2: Not equal to
c = 10
d = 20
print(c != d)  # Output: True

# Example 3: Greater than
e = 15
f = 10
print(e > f)  # Output: True

# Example 4: Less than
g = 5
h = 8
print(g < h)  # Output: True

# Example 5: Greater than or equal to
i = 7
j = 7
print(i >= j)  # Output: True

# Example 6: Less than or equal to
k = 3
l = 5
print(k <= l)  # Output: True

Using Comparison Operators in Conditional Statements

Comparison operators are often used in conditional statements to make decisions in your code.

Example:

age = 18

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Output:

You are an adult.

Conclusion

Comparison operators are essential for making decisions in your Python programs. By understanding and using these operators, you can compare values effectively and control the flow of your code based on conditions. Mastering comparison operators will help you write more logical and efficient programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top