Python - Comparison Operators
Python provides operators that can be used to compare values or values within variables. As as the name implies.
The comparison operators include equal to and not equal to operators. Also known as equality operators.
Both comparison operators, equal to(==
) and not equal to(!=
) gives resultant value in boolean i.e either True
or False
after evaluation.
Equal to(==
) operator(double equal) checks, whether operands surrounding equal to operator are same or not. Whereas the single equal(=
) is used for assigning RHS(Right Hand Side) value or expression to LHS(Left Hand Side).
The not equal to(!=
) operator in Python checks, whether operands surrounding operator are different or not.
In this article, you will find Comparison operators provided by Python.
Comparison operators
Basic comparisons performed on operands/variables with the use of equality operators.
Operator | Description | Example |
---|---|---|
== | Equal | a == b |
!= | Not Equal | a != b |
- Both of these operators
==
and!=
are binary operators. - These operators also follow the same general structure of
Operand
Operator
Operand
, meaning that an operator is always surrounded by two operands. - For example, an expression
a == b
is a binary operation, where a and b are the two operands and == is an operator. - If value of
a
&b
are same then you will getTrue
as value elseFalse
.
Example for different value in operands
a = 12
b = 24
print(a == b)
#Output: False
print(a != b)
#Output: True
Example for same value in operands
a = 12
b = 12
print(a == b)
#Output: True
print(a != b)
#Output: False
Generally these operators are use with if
statements.
Program to check whether the entered number is zero or non-zero
# ZeroNonZero.py
num = int(input('Enter integer: '))
if num == 0 :
print('Zero')
else :
print('Non-zero')
Hope you like this!
Keep helping and happy 😄 coding