4.2.5 The "if" statement block

View

The “IF statement” block is one of the main blocks in the control block. They are color-coded yellow and are used to execute a section of code only when a condition specified is true. It is often combined with repetition (repeat commands).

 

Example

The example below instructs the sprite to move 10 steps when the green flag is clicked and to say “You’re touching the edge” when the sprite reaches the edge and then the loop stops.

 

Figure 115: Code using if statement block

An “If statement” block works when you want to execute a section of code only when a specified condition is fulfilled.  The “if statement” blocks comes in two types: the “If statement” block and the “If-else statement” block.

Sometimes you wish to execute one section of code when a condition is true, and a different section of code when the condition is false. The code following the “if” is executed when the condition is true, while the code following the “else” is executed when the condition is false. This is called a “two-way branch”.


Example:

If, for example, the sprite does not reach the edge and you want the sprite to say “You did not touch the edge”, we can use the “If-Else” block as in the figure below.

 

Figure 116: Using If-Else control blocks

The example above instructs the sprite to move 10 steps when the green flag is clicked. If after the 10 steps the sprite has not reach the edge, then the sprite will say “You did not touch the edge” and will move 10 more steps. If after this again it has not touched the edge, it will say again “You did not touch the edge”. When it reaches the edge, then it will say “You’re touching the edge” and will stop.

Last modified: Wednesday, 29 September 2021, 4:57 PM