What are Relational Operators in Python?

Relational Operators are also known as comparison Operators. Though Python is capable of performing 100% of mathematical operations, but more than 80% of the job done by computers these days is of non-mathematical nature. 

Most of the time we are perform comparisons. Think about when you search something on Google? What do you think Google will do with your “search criteria”. Google simply compares that with its database.

List of Relational Operators

Relational Operators are used to compare two or more values to draw some facts from a data and take decisions on the basis of the result of comparisons.

Relational Operators Example Output Explanation
<

 10 <5

False Since 10<5 is False
> 10 > 5 True Since 10>5 is True
<= (Less than or Equal to) X=10
Y=20
print(X<=Y, X<=10)
True        True Since both “X is less than Y” and “X < or equal to 10” is True
>= (Less than or Equal to) X=10
Y=20
print(X>=Y, X>=10)
False      True Since both “X is greater than Y” is False and “X < or equal to 10” is True
!= X=10
Y=20
print(X!=Y, X!=10)
True        False Since both “X is not equal to Y” is True  and “X is not equal to 10” is False
== X=10
Y=20
print(X==Y, X==(Y/2))
False       True Since both “X is equal to Y” is False  and “X is equal to Y/2” is True

So we can see that relational operators always reply back or return back boolean values – True or False. At times it is very essential to determine some condition is true or false – to take decisions.

Look at the situations below:

  • We must know if percentage is above 85% or not – to allot Science Stream, or
  • It is required to compare to find out marks are below 40% or not – to find out stuent has passed or failed.
  • Compare and find out if ordervalue is above certain limit or not – to give some offer or discounts to the customer.
  • We must compare the age of a person – to find out whether person is eligible fo marriage or not.

So we can use these relational operators programmatically to compare and branch control to different segments of the program so as to carry out required operations automatically. Look at the examples  below:

Examples:

X=10
Y=20
if X<Y:
    print(X*X*X)
    print(Y*Y)
else:
    print(Y*Y*Y)
    print(X*X)

Output:

1000
400

So we can observe that the program above uses relational operators to compare X and Y and depending upon that it is able to branch the control to appropriate code block. Since X<Y is true cube of X and square of Y is printed as output. (Conditional statement – “if” wll be cred in th coming sections.

Learn more about operators used for comparisons in the field of Computer Science