To be or not to be that is the expression!
True or false: It’s very difficult to understand what boolean expressions are.
The word boolean was named after George Boole, who invented boolean logic in the mid-1800s. Boolean logic is a subset of boolean algebra but don’t let that scare you. It’s very simple to use and just like the coding terms I demystified in my previous series of articles, this too is something you use daily.
What exactly is boolean logic? Boolean logic is any expression that can be evaluated to one of two possible values.
Whoa, that is still a mouthful! Can you simplify it more? The statement – Can you simplify it more? – is a boolean expression that resolves to only one of two answers. In this case Yes or No. Other common examples are statements that resolve to true/false, off/on, stop/go.
As you can see you use and answer boolean expressions all the time:
The sky is blue: True
Did Bob or Bill eat pancakes for dinner? No Would you like me to turn on the lights? Yes Do Kim and Suzie play netball? No
See, so simple even a two-year-old can evaluate a boolean expression. “Do you want a cookie?” Yes.
Now let’s get nerdy!
How are boolean expressions used in coding? Boolean logic uses three simple operators: OR, AND and NOT. An example of how these may be used is when schools send out emails to parents. The school has a database of parent email addresses but they don’t just email every single parent each time they send an email out. The database uses Boolean logic to select which email addresses to include: if a parent is in the selection of email addresses that resolves to true then the parent will receive an email notice. The others will not because they resolve to false.
Let’s say the school wants to send out a notice to all parents of year 6 students that are 11 years old. What operator would be used here?
If you said AND you got it!
If student = ‘Year6’ && studentAge = 11 then this statement is true so the program will sendNotice() to that student’s parent.
Many coding languages use the && operator to represent AND
If a school wants to send out notices to all parents of year 5 or year 6 students what logic operator is used?
If you said OR, you are correct. The code that runs this may look similar to:
If student = ‘Year5’ || student = ‘Year6’ then sendNotice()
In many coding languages, the || operator represents OR.
Now, what if a notice needed to go out to all parents in the school except parents of new entrants? In this case, the NOT operator works best.
If student != “Year0” then sendNotice()
Can you guess what operator is the NOT operator?
Take a moment and reflect upon these logic operators. When and how do you use them in your daily life?
Back to my original question, are Boolean expressions difficult to understand? Hopefully, after reading this article your answer resolves to no.