Boolean Expressions
A Boolean expression (named for the mathematician George Boole) is an expression that can be either true
or false
.
For example:
- My favorite color is blue == true
- I am afraid of the dark == false
- Coding is fun after all == true
In the logic of computers, we test relationships between numbers:
1 2 3 | 15 is greater than 20 == false 5 equals 5 == true 32 is less than or equal to 33 == true |
let’s think of this in terms of code and variables:
1 2 3 | x > 20 – depends on the current value of x y == 5 – depends on the current value of y z <= 33 – depends on the current value of z |
The following are standard boolean operations in Processing:
1 2 3 4 5 6 | > greater than < less than >= greater than or equal to <= less than or equal to == equal to != not equal to |
“If” Statements
Conditionals operate within the sketch as questions. Is 30 greater than 10? If the answer is yes (i.e., true), you can choose to execute certain instructions (such as draw a rectangle); if the answer is no (i.e., false), those instructions are ignored. This introduces the idea of branching; depending on various conditions, the program can follow different paths.
With the question, if the mouse is on the left side of the screen, draw a rectangle on the left side of the screen, you would code it as follows:
1 2 3 4 5 6 7 8 9 10 11 12 | function setup() { createCanvas(windowWidth, windowHeight); } function draw() { background(0); if (mouseX < windowWidth/2) { fill(255); rect(0, 0, windowWidth/2, windowHeight); } } |
In the above code, remember that mouseX
is a system variable that always holds the current X coordinate of the mouse. windowWidth/2
is the X coordinate of 1/2 of the screen. Together, mouseX < windowWidth/2
is true when the X position of the mouse is on the left half of the screen.
Complete Activity 16