Learn How to Think with Karel the Robot. Chapter 11. Boolean Values, Variables, Expressions, and Functions

Chapter 11
Boolean Values, Variables, Expressions, and Functions

In this chapter you will learn:

  • Who was George Boole.
  • What is the so-called Boolean (logical) algebra.
  • About Boolean values True, False and Boolean variables.
  • That the comparison operators ==, !=, <, >, <= and >= yield True or False.
  • How to work with Karel’s GPS coordinates.
  • How to evaluate complex Boolean expressions.
  • That Karel’s sensors are Boolean functions
  • That the if statement and the while loop both expect Boolean values.
  • How to create an infinite loop and when such a loop can be useful.

11.1. George Boole

George Boole was an English mathematician and philosopher. During his era, logic was considered to be part of philosophy rather than mathematics. One of his greatest contributions is the mathematical formalization of logic which he introduced in his famous 1854 book The Laws of Thought. There he explained that logical processes and conclusions can be written using mathematical symbols and formulas, and he introduced his legendary Boolean algebra which long after his death became a fundamental pillar of modern computer science.


PIC

Figure 11.1: *

George Boole (1815 - 1864).


11.2. Quick introduction to logic

You certainly know the Harry Potter movies whose main stars are three young characters Harry Potter, Hermione Granger and Ron Weasley. One can state various things about them which are either true or false. For example, "Harry was born in the Suffolk village of Lavenham" is true. Actually, let’s use True instead of just "true" to emphasize that the evaluation of the statement resulted into a logical value. Analogously, evaluating the statement "Hermione Granger is a boy" yields False.

To simplify all this, let’s denote the statement "Harry was born in Lavenham" by A and the statement "Hermione Granger is a boy" by B. Then A is True and B is False.

From Chapter 4 you already know the logical operations and, or, not. The operation not flips True to False and vice versa. For example, saying "Harry was born in Lavenham" and "Hermione Granger is not a boy" is True. This can be abbreviated as

A and (not B) is  True
Saying "Harry was not born in Lavenham" and "Hermione Granger is not a boy" is False. In short, this is the same as
(not A) and (not B) is  False
It is also False to say that "Harry was born in Lavenham" and "Hermione Granger is a boy":
(not A) and B is  False
Finally, also saying that "Harry was not born in Lavenham" and "Hermione Granger is a boy" is False:
A and B is  False
Since A is True and B is False, the above four statements can be summarized in a table:

   True   and  True    is  True

  False   and  True    is  False

  True  and   False    is  False

False   and   False    is  False

This table is called the the truth table of the and operator.

Now imagine that you like to eat pizza. But not all kinds - you will only eat a pizza if it has cheese or salami on it. So, when we abbreviate "has cheese" by A and "has salami" by B, you will eat a pizza only if A is True or if B is True:

A or B is  True
If they bring you a pizza which only has cheese (A is True) but not salami (B is False), you will still eat it:
A or (not B) is  True
And you will also eat a pizza which does not have cheese (A is False) but has salami (B is True):
(not A) or B is  True
However, when a pizza has neither (both A and B are False), you will not eat it:
(not A) or (not B) is  False
These four outcomes can be summarized in another important table which is called the truth table of the or operator:

   True   or  True   is  True
 False    or  True   is  True

 True   or  False    is  True

False   or  False    is  False

11.3. What is Boolean algebra?

Looking at the truth tables above, G. Boole realized that if True was replaced by a nonzero number (let’s just say "nonzero") and False by 0, then the first table (of the and operator) would look just like multiplication:

nonzero  ⋅ nonzero  =   nonzero

       0 ⋅ nonzero  =   0

       nonzero  ⋅ 0 =   0
              0 ⋅ 0 =   0
Since then, the and operation has been called logical product. And similarly, the truth table of the or operator looks just like addition, and therefore has been called logical sum:

nonzero  + nonzero   =   nonzero
       0 + nonzero   =   nonzero

       nonzero  + 0  =   nonzero

               0 + 0 =   0
You may have noticed that the first line has a minor imperfection, because the sum of two nonzero numbers can be zero (for example when adding -1 and 1). But this imperfection goes away when we limit ourselves from all nonzeros to only positive nonzeros.

11.4. Boolean values and variables in Karel

Karel provides the keywords True and False. For example, typing

1print(True)

will display


PIC


And when typing

1print(True)

one will obtain


PIC


The operations and, or, not can be applied to the Boolean values True and False directly. For illustration, this short program will reproduce the truth table of the and operator:

1print(True, ~ and~, True, ~ is~, True and True) 
2print(False, ~and~, True, ~ is~, False and True) 
3print(True, ~ and~, False, ~is~, True and False) 
4print(False, ~and~, False, ~is~, False and False)

Output:


PIC


This program will reproduce the truth table of the or operator:

1print(True, ~ or~, True, ~ is~, True or True) 
2print(False, ~or~, True, ~ is~, False or True) 
3print(True, ~ or~, False, ~is~, True or False) 
4print(False, ~or~, False, ~is~, False or False)

Output:


PIC


The True and False values can be assigned to variables. Such variables then become Boolean variables. For example,

1b1 = True 
2print(b1)

will display


PIC


and

1b2 = False 
2print(b2)

will yield


PIC


The logical operations and, or can be applied to the Boolean variables. As a last example, let’s reproduce the truth table of the and operator again:

1t = True 
2f = False 
3print(t and t) 
4print(f and t) 
5print(t and f) 
6print(f and f)

Output:


PIC


11.5. GPS sensors gpsx and gpsy

Karel has his own GPS device that reveals his GPS coordinates in the maze! The device comes in the form of two built-in functions gpsx and gpsy which return the current column and row the robot is in, respectively. Importantly, when Karel is in the left-most column, his gpsx is zero. When he is in the bottom row, his gpsy is zero.

For illustration, let’s have Karel traverse the entire maze from West to East and display his gpsx coordinate in each grid square:


PIC


Here is the program the robot will use:

1while not home 
2  print(gpsx) 
3  go 
4print(gpsx)
picture

Output:


PIC


In the output you can see that the gpsx coordinate of the right-most column (where the home square is) is 14.

Next, Karel will ascend a snowy mountain, reporting both his gpsx and gpsy coordinates in every grid square he visits:


PIC


This is the corresponding program:

1while not home 
2  while wall 
3    print(gpsx, gpsy) 
4    left 
5    go 
6    right 
7  print(gpsx, gpsy) 
8  go 
9print(gpsx, gpsy)

Output:


PIC


In the output you can see that the gpsy coordinate of the top row of the maze is 11.

11.6. Comparison operators ==, !=, <, >, <= and >=

You first saw these operators in Chapter 7, but at that time we did not know yet that they returned Boolean values True or False. That’s what they do! For illustration, look at this sample program which displays True:

1print(1 < 2)

Also, look at another sample program whose output is False:

1print(1 == 2)

Of course, Boolean values returned by the comparison operators can be stored in Boolean variables. This program displays True:

1n = 5 
2b = n == 5 
3print(b)

Using parentheses will improve the readability of the previous program:

1n = 5 
2b = (n == 5) 
3print(b)

And here is one last, slightly more complex example whose output is False:

1done = False 
2n = 5 
3m = 9 
4b = (n == 5) and (m < 10) and done 
5print(b)
picture

11.7. Boolean functions

You have already seen quite a few functions which returned numbers, as well as one function which returned text strings (function row in the Morse translator project on page 864). Boolean values True and False can normally be returned by functions as well. A function which returns a Boolean value is called Boolean function.

As you know, Karel has a sensor north which he can use to check whether he faces North. He does not have similar sensors for South, East or West. Therefore, let’s define a Boolean function south which returns True if Karel faces South and False otherwise:

1def south 
2  repeat 2 
3    left 
4  n = north 
5  repeat 2 
6    right 
7  return n

When Karel faces South,


PIC


the function returns


PIC


When he faces East, West or North,


PIC    PIC   PIC


it returns


PIC


As another example, let’s write a function border which returns True if Karel stands next to the border of the maze, and False when he stands in the interior:

1def border 
2  return (gpsx == 0) or (gpsx == 14) or (gpsy == 0) or (gpsy == 11)

As a last example, let’s write a Boolean function edible which returns True if Karel stands above an edible object, and False otherwise:

1def edible 
2  return pumpkin or corn or apple or cherry or candy or lollipop or pie or orange or banana or potato or coconut or popcorn
picture

11.8. Karel’s sensors are Boolean functions

All Karel’s sensors for obstacles, collectible objects, and containers are Boolean functions. So are the other sensorse such as north, home and empty. The only exceptions are the gpsx and gpsy sensors which return integer numbers.

To illustrate this, let’s put Karel one step away from a wall, have him display the value of the wall sensor, then have him approach the wall, and display the value of the sensor again:


PIC   PIC


Here is the corresponding program:

1print(wall) 
2go 
3print(wall)
picture

Output:


PIC


In the following example, Karel faces West. He will make four right turns, displaying the value of the north sensor before every turn:


PIC    PIC    PIC    PIC


The corresponding program,

1repeat 4 
2  print(north) 
3  right

will output


PIC


11.9. The if statement revisited

You have already seen the if statement in many different forms. It can be used to avoid crashing into a wall in front of the robot:

1if wall 
2  left

Or it can be used to make sure that Karel can move forward safely:

1if not wall 
2  go

One can use it to check whether Karel has any objects in his bag:

1if not empty 
2  put

Or, one can use it to detect whether Karel is facing North:

1if north 
2  left

After seeing in the previous section that Karel’s sensors are in fact Boolean functions, you understand that the if statement expects a Boolean value. That’s how it decides whether its body will be executed or not.

The Boolean values True and False can be used with the if statement directly:

1if True 
2  print(~The body of this if statement will be executed always.~)

Although this seems to be of little practical application, it can be used to disable a condition and just let the code run. Or, the False value can be used to disable the body of the condition so that it never runs:

1if False 
2  print(~The body of this if statement will never be executed.~)

Especially for longer codes this is less work than having to comment out many lines. picture

11.10. Using the if statement to display debugging information

Displaying the values of important variables while the program is running is the oldest and most universal debugging technique. One can define one Boolean variable (named for example DEBUG) at the beginning of the code, and then use it in if statements throughout the program to enable debugging output:

1DEBUG = True # debug mode ON 
2 
3... 
4 
5if DEBUG 
6  print(~Debug info X =~, X) 
7 
8... 
9 
10if DEBUG 
11  print(~Debug info n =~, n) 
12 
13...

When the DEBUG variable is set to False, no debugging information will be displayed:

1DEBUG = False # debug mode OFF 
2 
3... 
4 
5if DEBUG 
6  print(~Debug info X =~, X) 
7 
8... 
9 
10if DEBUG 
11  print(~Debug info n =~, n) 
12 
13...
picture

11.11. Another look at the while loop

After reading Section 11.9 (page 962) it will come as no surprise that the while statement expects a Boolean value. When True, the body of the loop is executed. When False, the loop ends. To illustrate this, let’s have Karel look for a place to cross a cactus field, displaying the value of the cactus sensor on the way:


PIC


This is the corresponding program:

1left 
2while cactus 
3  print(cactus) 
4  right 
5  go 
6  left 
7print(cactus)

After the program ends, Karel stands in front of the opening:


PIC


And here is the program output:


PIC


picture

11.12. Infinite loop while True

By typing while True one can create an infinite loop. Infinite loops are used in Python and other programming languages, for instance to wait for user input or some other type of event, to simplify the code when the condition behind the keyword while is too complex, or to emulate the do-while loop.

We can illustrate the process of waiting for an event by tossing dice. Karel has a function randint(m, n) which returns a random integer between m and n (including m and n). So, calling randint(1, 6) is the same as tossing a die. Imagine that Karel is playing a game and must toss a dice until he gets a six.

This can be done using the regular while loop. But the code is cumbersome because the line with the randint function, as well as the line that displays the value, must be there twice:

1# Karel must toss dice until he gets 6: 
2def game 
3  n = randint(1, 6) 
4  while n != 6 
5    print(n) 
6    n = randint(1, 6) 
7  print(n) 
8  return 
9 
10# Main program: 
11game

Here is an alternative code which uses an infinite loop while True to emulate the do-while loop. It only needs to use the function randint and the print statement once:

1# Karel must toss dice until he gets 6: 
2def game 
3  while True 
4    n = randint(1, 6) 
5    print(n) 
6    if n == 6 # event occurred, exit loop 
7      return 
8 
9# Main program: 
10game

Sample output:


PIC


More about randomness and probability will be said in Chapter 12. There we will even show you that randomness can be used to solve difficult tasks which cannot be solved deterministically.

11.13. Review questions

Friendly reminder - for every question either none, one, or several answers may be correct.

QUESTION 11.1. Who was George Boole?

A
Australian musician who composed the song "True or False".
B
Host of the movie show "Truth or Consequences".
C
Russian programmer who created the video game "True or False"
D
English mathematician who studied logic.

QUESTION 11.2. What are the two values used in Boolean algebra?

A
Yes and No
B
True and False
C
True and Untrue
D
Truth and Lie

QUESTION 11.3. A is True, B is False. What is A and B?

A
True
B
False

QUESTION 11.4. A is True, B is False. What is A or B?

A
True
B
False

QUESTION 11.5. A is True, B is False. What is (not A) and B?

A
True
B
False

QUESTION 11.6. A is True, B is False. What is (not A) or (not B)?

A
True
B
False

QUESTION 11.7. a is 1, b is 2. What will the code print(a == b) display?

A
True
B
False

QUESTION 11.8. a is 4, b is 0. What will the code print(a != b) display?

A
True
B
False

QUESTION 11.9. Karel is in the right-most column of the maze. What will be the output of the code print(gpsx)?

A
0
B
1
C
11
D
14

QUESTION 11.10. Karel is in the left-most column of the maze. What will be the output of the code print(gpsx)?

A
0
B
1
C
11
D
14

QUESTION 11.11. Karel is in the second row from the top of the maze. What will be the output of the code print(gpsy)?

A
9
B
10
C
11
D
12

QUESTION 11.12. Karel is in the third row from the bottom of the maze. What will be the output of the code print(gpsy)?

A
0
B
1
C
2
D
3

QUESTION 11.13. What will the code print(north) display?

A
The word north.
B
It will generate an error message.
C
It will display True if Karel faces North.
D
It will display False if Karel does not face North.

QUESTION 11.14. What will the code print(home) display?

A
The word home.
B
It will generate an error message.
C
It will display True if Karel is at his home square.
D
It will display False if Karel is away from his home square.


Table of Contents

Created on September 27, 2018 in Karel.
Add Comment
0 Comment(s)

Your Comment

By posting your comment, you agree to the privacy policy and terms of service.