Conditionals activities

A conditional statement (Block) allows a program to test some condition and then based on the outcome of that test, to execute some code (Blocks) or not.

Let's try a program in Scratch to examine how this works in detail. The conditional statement we use first is a simple 'if' statement. You can find this type of block on the 'Control' panel. The 'if' block has a space for holding a diamond shape block. This type of block is called a 'boolean' and is an expression which evaluates to either 'true' or 'false'. For example, if we have a variable which holds some value it can be tested using an '=' operator to see if that value is the same as some value we specify. So, for example in the demonstration (Figure 1) the value of 'answer' is tested using '=' to see if it has the value 'yes'. If it does have that value then the test evaluates to 'true' and the blocks within the 'if' block will then be executed. If 'answer' has any other value then the '=' test will evaluate to 'false' and the blocks within the 'if' block will not be executed.

simple 'if' statement stack in Scratch.
Figure 1 Simple 'if' statement.

To understand how an 'if' statement executes build the stack shown in Figure 1 or download it. You might want to use the stepping mode again (from the 'Edit' menu) when running this program.

First run the program and when asked 'shall we execute the blocks' type 'yes' (without quotation marks) and press return so that the 'if' statement's condition evaluates to 'true' and blocks inside the 'if' statement are executed. Then run the stack again and type in anything except 'yes' and see how the statements inside of the 'if' block are not executed.

The 'if' statement is usually available in an extended form which has an additional 'else' part. The statement behaves as you saw above except that if the condition evaluates to false the blocks inside of the 'else' part of the statement are executed. The program in Figure 2 illustates the use of an 'if ... else ...' Block. You can edit the earlier program or download the program.

simple 'if ... else ...' statement stack in Scratch.
Figure 2 Simple 'if ... else ...' statement.

Run this stack twice just as you did the earlier stack, typing 'yes' the first time and, say, 'no' the second time. Again you might want to turn 'stepping' on so that you can see what happens more clearly.

This is the end of all the Scratch programmng activities. Please go back and continue with the main guide.


Back