If-statements are used to make programs more efficient. In this article, we will be defining and exploring the function of this concept. Log into your Scratch account and create a new project. We will use the simple project set up with one sprite.
What are If-Statements?
If-statements are used to run code only under certain conditions. The programmer sets a condition, which can either be true or false. If the condition is true, the code within the if-statement will run. An example of this in plain English is: If it is raining, bring an umbrella. This concept can be extremely useful for programs that produce different results based on different circumstances.
Setting up the If-Statement
Let’s demonstrate if-statements in Scratch. Navigate to the Events section of the block palette, and place the “When ⚑ clicked” block into the script area. This will be how most scripts are started, since the block defines where the code will start running when the green flag is clicked.
Like the first program we wrote, we need a “forever” loop to make sure the code keeps running for the duration of the program. Recall that the “forever” loop repeats only the included code inside the loop. If we didn’t have the “forever” loop, the code after the flag block would only run once, which is too short of a program for our purposes.
Next, select “if < > then” block from the Control section of the block palette, and clip it inside the forever loop. The if-then format means that if a given condition is true, then the code within the body of the if-statement will run. The body of the if-statement is the code that is placed inside the if-then shell. Your code should look like this so far.
Setting up the If-Statement
Every if-statement needs a condition, which tells the program whether to run the body of the if-statement or not. A condition evaluates to true or false, and if it is true, the code that makes up the body will run. For example, the condition could be “the drink is hot” or “the given number is greater than 10”.
Writing the body of the if-statement
Finally, we need to write the code that will run while the space key is being pressed. Drag a “move 10 steps” block inside the if-statement. The sprite will now move 10 steps forward when you press the space key! Test this out by pressing the green flag to start the program, and try pressing different keys. Notice the sprite only moves when the condition (space key pressed) is true.
Using multiple if-statements, we can write a pretty complicated program! Observe the code below. The sprite will move right when the right arrow is pressed, left when the left arrow is pressed, and so on. The “change x” and “change y” refer to the axis on which the sprite is moving.