Home » Learn Python » Conditions » Less Than, Greater Than

Less Than, Greater Than

When working with numbers, we can easily check if one value is greater than another, or less than another.

As with the equality test operator (==), these operators return True or False, so they can be used as part of an if statement, for example.

We can also check if two things are not equal to each other. The “not equal” operator returns True only if the two things being compared are not equal to each other.

We can use the following operators.

  • < “less than”
  • > “greater than”
  • <= “less than or equal to”
  • >= “greater than or equal to”
  • != “not equal”

In this program I’ve printed both a text version of each condition, and the result of actually applying the condition to some numbers.

print("4 < 7", 4 < 7)
print("4 > 7", 4 > 7)
print("5 <= 5", 5 <= 5)
print("6 >= 4", 6 >= 4)

print ("5 != 4", 5 != 4)
4 < 7 True
4 > 7 False
5 <= 5 True
6 >= 4 True
5 != 4 True

More String Comparison

Surprisingly, these operators also work with strings, as well as integers and floating-point numbers. With strings, less than or greater than basically work on dictionary order.

There is an important caveat though; these operators are looking at the order of letters in the Unicode character set. This is a vast table of characters, in which capital letters occur before the lowercase letters, which explains the result below.

print('"dog" > "cat"', "dog" > "cat")
print('"Dog" > "cat"', "Dog" > "cat")
"dog" > "cat" True
"Dog" > "cat" False

Of course in practice you are unlikely to want to compare two literal “hard-coded” values (two values you’ve literally typed into the program), because you could work that out without Python’s help. It’s more likely that one or both of the values you’re comparing would actually be variables, then you’re comparing whatever values the variables refer to, and those may have been calculated in your program, or derived from input.

Leave a Reply

Blog at WordPress.com.

Discover more from Cave of Python

Subscribe now to keep reading and get access to the full archive.

Continue reading