(MAI) Conditionals, Boolean and Logic Operators Lesson
Conditionals, Boolean and Logic Operators
Conditionals, conditional statements, or conditional expressions are all terms that are used to refer to how a computer makes decisions. Conditionals ask a question and check to see if the answer is true or false. The questions are asked in the form of an if statement. When the answer to the if statement is true, the condition will execute.
Conditionals allow the app to ask questions and determine which blocks to execute based on the answer.
Let's see an example of checking a condition when a button is pressed. When the button is pressed, the question is asked, "is the background red?". If the background is red, it will change to blue, else it will change to red. This acts as a toggle button to change the background from red to blue and from blue to red.
Below is an example of the algorithm in text form, flowchart and the programming blocks in App Inventor.
Multiple if statements
When you have multiple if statements, every if statement that is true will execute. You have to be careful when using this logic and make sure you want every if statement that is true to execute. Examine the code below. Why is the multiple if structure not a good choice for the code below?
Using an if and else if structure.
Using an if and else if structure, only one condition will execute. If the first if statement evaluates to true
, the statements associated with that if
are executed, and the control exits the program block. However, if the first if is not true, control continues down to the else if statement. The control flow will continue down until it reaches an else if statement that is true. As soon as it reaches a true condition, it will execute and control will exit the conditional statement. Since there is no else in the code below, if none of the conditions are true, nothing will happen when the button is clicked. This is a better solution to the multiple if structure above.
App Inventor conditional blocks are found in the Control drawer of the Built-In palette.
You can extend the block with as many else and else if branches as you'd like by clicking the blue icon.
Boolean Expressions and Logic Operators
You can plug any Boolean expression into the "test" slot of these blocks. A Boolean expression is a mathematical equation that returns a result of either true or false. The expression tests the value of properties and variables using relational and logical operators. You can also test multiple conditions by using the Logical Operators AND and OR.
Go through the learning object on Boolean Expressions and Logic Operators.
[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION