![]() | Variables: Remembering Stuff |
A computer has a memory and can remember stuff. To get a computer to remember stuff, you use variables. A variable is a piece of information with a name for that information.
Let's say you're shopping for groceries, and you need to buy five apples. You can tell the computer to remember how many apples you need to buy. You can use a variable for this.
In the blue Program Area on the left, type "apples=5;"
When you run the program, the computer will now store the number 5 in its memory. It will give that piece of information the name "apples."
To get the information back from the computer, you simply tell the computer the name of the information that you're looking for. The computer will look in its memory to find that information and give it back to you.
At the end of the program, type "show(apples);" When you run the program, the computer will notice that apples is a variable. It will look in its memory and show you that it remembered that you put 5 there earlier in the program.
Variables can be given any name that doesn't have any weird symbols in it. The variable name can have numbers in it as long as the name doesn't start with a number. Here, we have a grocery list of things we have to buy.
Make sure you spell the variable the same way every time. And make sure you don't mix up your upper case and lower case letters! If you use a variable that the computer does not know about, or if you spell a variable incorrectly, the computer will complain.
You can use variables in math. For example, instead of using "show(2+4);" you can use "show(lettuce + celery);" They're the same. Try it out.
You can also do math and put everything in a variable. You can even use variables in the math. Look here at three different ways to put things inside of the vegetables variable. They're all the same.
Suppose a friend is baking an apple pie and asks you to buy two extra apples. To do that, you can just take the old amount of apples that you wanted and add two to it. Then your grocery list will have two extra apples in it.
One weird thing with variables is that the computer forgets everything each time the program is run. So at the start of the program, you must set all the variables again.