Two Quick Examples

To help you become more comfortable with working with variables, let’s look at two quick examples. In the first example, shown next, a script has been created that when executed will display the value assigned to a variable named Counter. Remember, by default every variable that you create has a reporter block with an associated monitor, which Scratch displays by default on the stage.

Note

To set up and run this example, you must create a new application and add a variable named Counter to it and then add the script to the application’s default script.


This script has been set up to execute whenever the green flag button is pressed. It uses a control block to set up a loop that repeats the execution of two embedded code blocks a total of 10 times. Each time the loop executes, the value assigned to a variable named Counter is increased by 1. The next statement pauses the loop for one second before allowing it to continue running.

By default, Scratch assigns a default value of zero to all new variables, which is why the first time you run the previous script, it counts from 1 to 10. However, if you run it again, you will notice that it will count from 11 to 20. If you want, you can change this behavior by explicitly assigning an initial value to the Counter variable, as demonstrated in the following example:

Here, the value of Counter has been set to 0 through the addition of a new variable block at the beginning of the script, immediately after its hat code block. As a result, no matter how many times this script executes, it always counts from 1 to 10.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.190.120