When writing a program, we often need to check if a value is correct or compare two values.
Comparison operators allow us to compare values and evaluate their relationship. Rather than evaluating to an integer, they evaluate to
false, AKA boolean values. Expressions that evaluate to boolean values are known as boolean expressions.
Comparison operators include:
- Less than
<— value to the left is less than the value to the right:
2 < 6
- Greater than
>— value to the left is more than the value to the right:
14 > 5
==— value to the left is equal to the value to the right:
3 == 3
Note: we use a double-equal sign to show that we’re checking a value, rather than setting it equal to something, like we would with a variable. Some languages even use a triple-equal sign
=== to super-triple-check!
There are two main instances where we use comparison operators:
If we have an unknown quantity. What if we knew that we needed a half pound of strawberries, but we didn’t know the weight of each strawberry? We could weigh the strawberries and see if the total weight equals a half pound.
strawberry_weight = ? is (strawberry_weight == .5lb)? => true
If we need to compare two known values. If we’re making a salad that’s super citrusy, then we need to make sure we have more oranges than bananas. If that’s false, I’ll have to add more oranges.
bananas = 5 oranges = 3 is (oranges > bananas)? => false
For once, let’s compare apples and oranges.
Our fruit salad recipe gives us a couple options for apple to orange ratios.
If we want a balanced salad, we should have three apples and three oranges.
If we want a more citrusy salad, we should have five oranges and three apples.
If we want a less citrusy salad, we should have four apples and two oranges.
From left to right, follow the provided recipes and select the correct comparison operator for each one.
Why is it helpful to be able to check or compare different values?