Russian Translation Coming Soon.
Tutorial Four - Variables
In the previous tutorials, we learned how to print messages and numbers on the screen and how to do math using the print command.
This is very good to know how to do, but it doesn't really help us use the full power of the computer. Computers do more than simple things like add numbers and print messages. A big part of what computers do is to store information, so it can be used later.
This is where "variables" come in handy. Variables are a way to save a message or a number so that you can use it later.
Let's try an example.
a = 4 print a
When you type that in and press Run, the computer should print the number 4 in the Text Output window. But how does it know to do that? You told it to print a.
Well, this is where variables come in. In the first line, the equal sign means that you want to store the number 4 in "variable" a. You can change that number 4 to any number and run the program again. You'll notice that the number that gets printed changes, even though you didn't change the print command at all!
But wait, it gets better. You can use variables that store numbers as if they were actually numbers. That means we can add and subtract variables just like numbers. Let's try it.
a = 4 print a + 7
Now when you run the program you should get 11 as a result. Since the number 4 was stored in variable a, when you add 7 you get 11. If you change the 4 to another number, you'll get that number added to 7 as a result.
But why not just save all of the trouble and use 4 instead of a to begin with? Well, the nice thing about variables is that you can use them over and over. Let's say you wanted to add a whole bunch of numbers and see the results:
a = 4 print a + 1 print a + 2 print a + 3 print a + 4 print a + a
See? Now we've done five calculations, and if we wanted to change them all, all we'd have to do is change the 4. You can even use the variable more than once in the same line. The last line in our program did that, so we can add a number to itself. Variables save us lots of time that way. We'll see more ways that variables help us in later tutorials.
Notice that we've only stored numbers in variables so far. Variables are more flexible than that -- they can store messages too:
a$ = "Hey there" print a$
The only difference between storing numbers and messages in a variable is that when you store messages, the variable has to end in a dollar sign ($). Otherwise when you try to run the program, you'll get a "syntax error."