Skip to main content
Published on

Comparison Operators in Python

Share:

Introduction

Comparison operators are essential in programming for comparing values and determining the relationship between them. In Python, these operators are frequently used alongside conditional statements, such as if, to make decisions based on comparisons.

The Main Comparison Operators

  • ==: Checks whether two values are equal.
  • !=: Checks whether two values are different.
  • >: Checks whether the value on the left is greater than the value on the right.
  • <: Checks whether the value on the left is less than the value on the right.
  • >=: Checks whether the value on the left is greater than or equal to the value on the right.
  • <=: Checks whether the value on the left is less than or equal to the value on the right.

Logical Operators

In addition to comparison operators, we have logical operators that allow combining multiple conditions:

  • and: Returns true if both conditions are true.
  • or: Returns true if at least one of the conditions is true.

Usage Examples

x = 15
y = 25

if x == y:
  print('x is equal to y')
elif x != y:
  print('x is different from y')
elif x > y:
  print('x is greater than y')
elif x < y:
  print('x is less than y')
elif x >= y:
  print('x is greater than or equal to y')
elif x <= y:
  print('x is less than or equal to y')

# x is different from y

Combining Operators

We can combine comparison operators with logical operators to check multiple conditions:

age = 17
salary = 1500

if age >= 18 and salary > 1000:
  print('Eligible for credit.')
else:
  print('Not eligible for credit.')

# Not eligible for credit.

Conclusion

Understanding comparison and logical operators in Python is crucial for building programs that can make decisions based on specific criteria. Regular practice and experimentation are recommended to become fully comfortable with these concepts.

Happy coding!