Anyone Can Code.


Comparison Operators

Avi Bhattacharya, Sammarth Kumar

Comparison Operators are used to compare two values. They return True or False based on the condition.

Operator Operation
== Checks whether two values are equal
!= Checks whether two values are not equal
> Checks whether one value is greater than the other
Checks whether one value is less than the other
<= Checks whether one value is lesst han or equal to the other
>= Checks whether one value is greater than or equal to the other

We will start by using comparison operators with numbers.

    x = 6
    y = 5
    print(x > y)
    print(y < x)
    print(y+1 >= x)
    print(y <= x)
False True False True True True True

We can also use comparison operators with sequences. When used in a sequence, the interpreter checks the value of each element in the sequence starting from the first element in both sequences. For numbers, it compares the number values, but for strings it compares the ASCII values of each character. To see more about ASCII encoding, check out this video. For the purpose of this tutorial we will be sticking to the English Alphabet. The ASCII value for capital A is 65 and for lowercase a it is 97.

    x = "He"
    y = "Hi"
    print (x == y)
    print(x > y)
    print(x < y)
False False True

In this example, we see that "He" is less than "hi". In this example, since the first character of each string is the same, the interpreter moves on to the next characters, which are e and i. Since the ASCII value of "e" is less than that of "i", we get "He" < "Hi" .

We can also do the same with lists.

    x = [2,3,5]
    y = [2,4,4]
    a = ["a","b"]
    b = ["A", "B"]
    print(x > y)
    print(a < b)
False False

Here, x is less than y because 2 is equal to 2, but 3 is less than 4. Also notice how the interpreter did not check whether 5 is greater than 4 or not. Also, a > b because ASCII value of "a" is greater than that of "A".

Here's a graphic for a quick recap:

That's it for this tutorial! Click Next to access the next tutorial!

❮ Back

Next ❯

Copyright © 2021, Q-Programming | Created by Arjun Sodhi, Balpreet Juneja and Sammarth Kumar | Developed and Designed by Sammarth Kumar