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

OperatorNameDescriptionExampleOutput
==Equal toReturns True if both values are equala == bFalse
!=Not equal toReturns True if both values are not equala != bTrue
>Greater thanReturns True if the first value is greatera > bFalse
<Less thanReturns True if the first value is smallera < bTrue
>=Greater than or equal toReturns True if the first value is greater or equala >= bFalse
<=Less than or equal toReturns True if the first value is smaller or equala <= bTrue

Examples of Comparison Operators

1. Equal to (==)

The == operator checks whether two values are equal.

a = 10 b = 20 # Equal to print(a == b) # Output: False

2. Not equal to (!=)

The != operator checks whether two values are not equal.

a = 10 b = 20 # Not equal to print(a != b) # Output: True

3. Greater than (>)

The > operator checks whether the first value is greater than the second.

a = 10 b = 5 # Greater than print(a > b) # Output: True

4. Less than (<)

The < operator checks whether the first value is less than the second.

a = 10 b = 20 # Less than print(a < b) # Output: True

5. Greater than or equal to (>=)

The >= operator checks whether the first value is greater than or equal to the second.

a = 10 b = 10 # Greater than or equal to print(a >= b) # Output: True

6. Less than or equal to (<=)

The <= operator checks whether the first value is less than or equal to the second.

a = 10 b = 20 # Less than or equal to print(a <= b) # Output: True

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.

a = 15 b = 10 if a > b: print("a is greater than b") else: print("a is not greater than b") # Output: a is greater than b

Example with Multiple Comparisons

You can use comparison operators in conjunction with logical operators to check multiple conditions.

a = 15 b = 10 c = 20 # Check multiple conditions using 'and' logical operator if a > b and a < c: print("a is between b and c") # Output: a is between b and c

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.