THE education site for computer science and ICT

3. Selection: Comparisons

Other than for the most basic tasks, most programs involve having to make choices. Maybe you want to do one thing if a condition is true and another if it is not. The process of determining which choice to take is called 'selection'.

Comparisons

Selection always involves a comparison operation, where you check whether certain conditions are met. The comparison operators are

Meaning Symbol
Greater than
>
Less than
<
Greater than or equal to
>=
Less than or equal to
<=
Not equal to
!=
Are the same
==

The last one (==) is often confused with the equal sign =. They are not the same thing.

If you use =, you are setting (aka assigning) one value to be equal to another.

If you use ==, you are comparing one value to another to see if they are equal.

For example if you say "chalk = cheese", then you are telling the computer that chalk is cheese. If you say "chalk == cheese", you are asking the computer to check whether chalk is cheese.

Combine comparisons

You can use boolean operator to make two comparisons in the same statement, like this

`                     a < 2 AND b > 4`

The boolean AND operator means that both comparisons need to be true for the evaluation to be true. Other common boolean operators used are OR and NOT.

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: What is selection in programming?