A variable is a container of a value.
Consider the shoes you are wearing now. Those shoes are variable, and their values are your feet. If someone puts on your shoes for a moment, then your shoes no longer contain your feet, that is, your shoe variable contains a different value (feet). You see, your shoes are called a variable because their values may vary or may be different sometimes.
Also, your shoes can hold only one foot at a time. Similarly, a variable can only hold one value at a time.
The Answer block in Scratch is a variable. It’s value or data can change overtime depending on what the user typed in, and it can contain only one value at a time.
Here’s the problem
This Scratch project below has only one variable which is the Answer block. The character asks for two pieces of data: the user’s name and age. The sprite can ask for the user’s name, put the user’s answer in the Answer variable block, and then display it. So far at that point, all is good.
The problem is when you need to hold another kind of data, say the user’s age. So your sprite may allow the user to type in his or her age, put the age in the Answer block, and display the user’s age on the screen. The user’s age can be displayed, but the user’s name is gone. This is because a variable can only hold one value at a time. Consider the example below.
The solution
The solution to this is to add another variable. Here’s how to do it.
Step 1: Go to the Variables Block section (it’s orange).
Step 2: Click the Make a Variable button to create your own variable (it is a white button)
Step 3: Give it a meaningful name. I will use userAge in this example. Leave the ‘For all sprites’ option selected, then click Ok.
Step 4: Then as soon as you ask your user to enter his or her age, put that data into your userAge variable. This means that you will have to use the Set variable to Answer block (it’s orange).
Step 5: Then you can now display the value of your variable by using the userAge in the Say block instead of the Answer variable block.
Here’s the final set of code blocks. Notice that I added a variable to hold the user’s name.
Here’s an example
Notice that the sprite can now display the user’s name and age anytime he wants since both of these data have variables holding it.
Show us the Scratch project you made similar to this using variables. Paste the link to your Scratch project in the comment box below.