Relational Operators in Python


☞ They give True or False as a result.

☞ They are binary operators.

☞ When truth value converted to int, it becomes 1 or 0.

☞ These operators can be used to compare strings also.

☞ Only = = and != can work on complex numbers.

☞ Every non –zero value gives True and zero gives False.

☞ String is checked in dictionary order i.e. alphabetically

☞ ;Following are the relational operators. To see it precedence, check the precedence table.

<    ➺    less than
<=   ➺    less than or equal to
>    ➺    greater than
>=   ➺    greater than or equal to
!=   ➺    not equals to
==   ➺    equals to

☞== and != are known as equality operators.

Example

a=3<4
print(a)
b=3<=4
print(b)
c=3>4
print(c)
d=3>=4
print(d)
e=3!=4
print(e)
f=3==4
print(f)

Output

True
True
False
False
True
False

Special Cases :

Example : practice.py

a=True + 9
print(a)
print("---------")
b=10 > 9 >6
print(b)
print("---------")
c=7 == "7"
print(c)
print("---------")
d='a' == 97
print(d)
print("---------")
e=ord('a') == 97
print(e)

Output

10
---------
True
---------
False
---------
False
---------
True

Exceptional Cases :

☞ Equality operators can be used for int & float. (it will not check data type).

☞ It can also be used on int and boolean.

Example :

x=5 ==5.0
print(x)
print("----------")
y=5 < 6.5
print(y)
print("----------")
z=True == 1
print(z)
print("----------")
a= True < 5
print(a)
print("----------")
b= True == 5
print(b)

Output

True
----------
True
----------
True
----------
True
----------
False

Note :
1) Equality operators does not give error, and they check the type and content, and hence can be used for any data type.
2) If we apply relational operators other than equality operators on complex number, it will give TypeError: '>' not supported between instances of 'complex' and 'complex'