Skip to main content

Subsection 2.4.2 Boolean Expressions in Programming Languages

So now you see that you’ve been using Boolean expressions since about the time you could walk. When we talk to each other, we can be very flexible in how we state them (and all the other expressions that we use).

When we write code, however, we have to be more careful. We have to stick to the rules of the programming language that we’re using. Every programming language (since the very first one) provides one or more (typically more) ways that programmers can use Boolean expressions to describe the sequences of operations that their programs should perform.

Here’s a really simple Python program. Assume that NOW is the current year and BIRTHYEAR is the year in which you were born. Then this program, which could be part of the self-checkout procedure at your local convenience store, runs whenever you attempt to buy alcohol:

If NOW – BIRTHYEAR > 20: 
      print("Yea!  Buy all you want.") 
	else: 
	     print("Sigh.  Can I interest you in some water?") 

This program contains one Boolean expression, NOW – BIRTHYEAR > 20. When the program runs, the Boolean expression is evaluated. If it’s true (in other words, if the difference between the current year and the year in which you were born is greater than 20), then the first print statement will be executed. Else, if it’s not, the second one will be. Notice that this is an oversimplification of the real rules, which must look at what day it is. But you get the idea.

More complex Boolean expressions are generally allowed. We’ll revisit this issue after we’ve developed some tools for working with compound expressions.

Exercises Exercises

Exercise Group.

Consider the following program:

read(x, y) 
if x = 0 or y = 0: 
     print (“error”) 
else if x > y:
     print (x * y) 
 else: 
     print (x + y) 

Indicate, for each of the following program fragments, whether or not it is a Boolean expression (i.e., something with a truth value):

1.
x = 0
Answer.
Boolean expression
2.
x = 0 or y = 0
Answer.
Boolean expression
3.
x - y
Answer.
not a Boolean expression
4.
print (x – y)
Answer.
not a Boolean expression
5.
x > y
Answer.
Boolean expression
6.
x + y
Answer.
not a Boolean expression