python
  1. python-comparison-operators

Python Comparison Operators

Comparison Operators in Python are used to compare the values of two operands. These operators return Boolean values (True or False) depending upon the condition being true or false.

Syntax

operand_1 operator operand_2

where operator can be one of the following:

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to

Example

a = 5
b = 10
print(a == b)    # Output: False
print(a != b)    # Output: True
print(a > b)     # Output: False
print(a < b)     # Output: True
print(a >= b)    # Output: False
print(a <= b)    # Output: True

Explanation

In the above example, we have two variables a and b with values of 5 and 10 respectively. We are using comparison operators to compare these values.

The first comparison operator used is "==", which checks whether a is equal to b or not. Since a is not equal to b, the output is False.

The second comparison operator used is "!=", which checks whether a is not equal to b or not. Since a is not equal to b, the output is True.

The third comparison operator used is ">", which checks whether a is greater than b or not. Since a is not greater than b, the output is False.

The fourth comparison operator used is "<", which checks whether a is less than b or not. Since a is less than b, the output is True.

The fifth comparison operator used is ">=", which checks whether a is greater than or equal to b or not. Since a is not greater than or equal to b, the output is False.

The sixth comparison operator used is "<=", which checks whether a is less than or equal to b or not. Since a is less than or equal to b, the output is True.

Use

Comparison Operators are used to compare values and make decisions based on the outcome of the comparison. They are used in control statements such as if, elif and while to make decisions based on the outcome of the comparison.

Important Points

  • Comparison Operators return Boolean values, which are either True or False.
  • Comparison Operators can be used to compare numerical values as well as strings.
  • Comparison Operators can be used in control statements such as if, elif and while.

Summary

Comparison Operators are used to compare the values of two operands and return Boolean values. They are used in control statements to make decisions based on the outcome of the comparison. Comparison Operators are an important part of any programming language and form the backbone of decision making in programs.

Published on: