Python Relational Operators

Relational Operators

The relational operators are used in python when we try to establish a relation between two operands i.e. make a comparison. Some of the relational operands are:

  • > – Greater than
  • < – Less than
  • >= – Greater than equal to
  • <= – Less than equal to
  • = – Equal to

Example:

>>>a= 20 #declaring a
>>>b= 10 #declaring b
>>>print(a>b)
>>>print(a>=b)
>>>print(a<b)
>>>print(a<=b)

Output:

True #output for greater than
True #output for greater than equal to
False #output for less than
False #output for less than equal to

These is relational operators can also be used with string and Boolean datatypes. While comparing the string and Boolean datatypes it takes into consideration the characters one by one and compares them alphabetically i.e according to Unicode value. If the first character of a string is greater than the first character of the second string then it will automatically declare the first string to be greater and not check for the second character of both strings.

Example:

>>> ’dog’<‘goat’ #we take two strings to compare

Output:True

Here in the above program the value of the first character of the first string that is D is greater than the first character of the second string that is G. Hence the relation is proved to be true which is the output.


Example:>>>True>False

Output:True

In the above program we see a comparison between bool values true and false. As we all know that the value of true is one and the value of false is zero, since one is greater than zero the output is true.


Comparison between integer value and boolean values can be made since the boolean values have a value of one and zero which can be compared with an integer value.

Example:>>>10>True #we take two arguments to compare

Output:True

Here, in this program the value of 10 is greater than value of True i.e. 0. Therefore the output is true.


Chaining of relational operators:

When a series of relational operators are used with multiple operands then this process is known as chaining of relational operators. The overall answer will be true and false based on the condition that all the relation are satisfied. For example if all the conditions are true then the output will be true whereas even if one of the conditions do not satisfy then the answer will be false.

Example:>>>1<2<3<4 #taking multiple relational operators

Output:True

In the above example we have taken four numbers, One, two, three and four. Here since one is less than two, two is less then three and three and three is less than four, therefore all the conditions are satisfied and hence the answer will be true.

Example:
>>>1<2>3<4
Output:
False

This example is similar to the previous example but here two is not greater than three and hence the entire expression will have output as false.

Leave a Comment

Your email address will not be published. Required fields are marked *