We mentioned earlier that control flow in a program consists of events, conditional statements, and loops. Conditional statements execute certain sequences of statements depending on whether or not certain conditions are True. The following blocks represent conditional statements:
Simple if statements can be used when we want to execute a command only if some condition is True. If we want to execute one set of statements if a condition is True and a different set if that condition is False, we use an if-else statement.
Let's again read in a number from the user and then return the string "X is even" or "X is odd" depending on whether or not the number is odd or even. Build the following script in the Scripts panel but do not execute it yet:
Attach an if-else statement to the bottom of this series:
The rest of this is left as an exercise.
Excercise 2-4. Perform the following actions in order to finish the program.
Write an expression (not with blocks yet, just on paper) that will return True for an even number and False for an odd number.
First, we will need the mod operator. X mod 2 will be 0 for an even number and 1 for an odd number because even numbers have no remainder when divided by 2 and odd numbers always have a remainder of 1 when divided by 2. Thus, an expression that is True for an even number and false for an odd number is X mod 2 = 0.
Using the expression you just created, use Scratch blocks to represent it in the Scripts panel and then place it in the diamond-shaped operand of the if statement.
You will of course need the mod block and the equals block along with the variable X.
Now write two statements: [value of X] " is an even number." and [value of X] " is an odd number." Place these statements into the appropriate places in the if-else statement. Hint: You will need the join block from Operators and the say block from Looks.
The statement block directly below "if" will execute if the expression evaluates to True and the statement block directly below "else" will execute if the expression evaluates to False. Since X mod 2 = 0 is True for even numbers, the even number statement belongs directly under the "if" and the odd number statement belongs after the "else."
Run this program with several different numbers to test and see that it works:
When multiple "if" statements are needed, another "if" block can be placed in the else statement (as many as needed). A very useful feature in Scratch for this is the duplicate option which can be found by right clicking on a block that is in the Scripts panel. (You of course do not have to build the following script. It's just an example.)