Conditionals Statements

Resources:

Shiffman - 3.1 Introduction to Conditional Statements - p5.js
Shiffman - 3.2 The Bouncing Ball - p5.js
Shiffman - 3.3 Else and Else if, AND and OR - p5.js
Shiffman - 3.4 Boolean Variables - p5.js
p5 Examples: Conditionals
p5 Examples: If/else Statements
p5 Examples: Logical Operators

Syntax Introduced:

Relational Expressions:

Conditional Statements:

Logical Operators:

Conditional Statements

Conditionals allow a program to make decisions about which lines of code run and which do not. They let actions take place only when a specific condition is met.

The test must be an expression that resolves to true or false. When the test expression evaluates to true, the code inside the { (left brace) and } (right brace) is run. If the expression is false, the code is ignored. Code inside a set of braces is called a block.

Conditionals can be embedded to include more than one test to control which lines of code will run.

In the following example, the text expressions are "x > 100" and "x < 100". Because x is 150, the code inside the first block runs and the ellipse is drawn, but the code in the second block is not run and the rectangle is not drawn. Try changing the value of x to a number lower than 100. What happens when x = 100?

Find another example of conditionals here.

Nested Conditional Statements

In the following example, if x is greater than 100 and less than 300, the ellipse is drawn. If x is greater than or equal to 300, the line will be drawn. If x is not greater than 100, the rectangle is drawn. Because x is 420, only the line is drawn.

If/Else Statements

In the following example, if x is less than or equal to 100, then the rectangle is drawn. Otherwise, if x is greater than or equal to 300, the line is drawn. If x is between 100 and 300, the ellipse is drawn. Because x is 101, only the ellipse is drawn.

Find another example of if/else conditionals here.

Logical Operators

Logical operators are used to combine two or more relational expressions and to invert logical values. They allow for more than one condition to be considered simultaneously.

The logical operators are symbols for the logical concepts of AND (&&), OR (||), and NOT (!):

Expression Evaluation
true && true true
true && false false
false && true false
true || true true
true || false true
false || false false
!true false
!false true

If we consider a = 8 and b = 12, we'd follow these steps in order to resolve the expression (a > 4) || (b < 24):

In the following example, the expression "a > 5" must be true OR "b < 30" must be true. Since they are both true, the code in the block will run.

In this example, the expression "a > 15" is false, but "b < 30" is true. Because the OR operator requires only one part to be true in the entire expression, the code in the block will run. Try changing the code to logical AND instead of OR

Find another example of logical operators here.