What is a variable in programming
In the last lesson we said code is words that give orders in sequence. So where do the values those orders work with go? It's time for variables: boxes that hold values under a name.
To use a value again
When you calculate, you often need the same value again.
Take your age: to say "use this year's age for this, and for that too," you have to store that age somewhere.
Otherwise you'd have to write out the age every single time.
What happens if you don't store the value?
So we give a value a name and store it.
Once it's stored, you can take it out again anytime using that name.
This storage box is called a variable.
A variable is a labeled box
Draw a variable and you get a box.
You stick a label on the box and put a value inside, as in "put 25 in the box called age."
Choose a name and a value below and a box is made.
Choose a name and a value.
The label is what you call the box, and the value inside is what it holds.
Say "age," and the computer finds that box and takes out the 25 inside.
Know the name, and you can get the value.
The box stays, only the value changes
This is where variables really earn their keep.
The value in a box can be changed anytime: keep the label, swap the contents.
A game score is a good example. One box called score keeps getting new numbers.
Keep the box's name; change only the value.
The name "score" stayed the same, but the value inside kept changing.
It's called a variable because it can vary.
Thanks to that, code can behave differently depending on the situation.
Calculating with variables
There's one more good thing about variables: you can calculate with names instead of values.
Write "next year's age is age plus 1," and whatever the age is, you always get one year more.
Change the age with the slider below and the result follows.
Change the age and the result follows.
Because you calculate with the name instead of writing the value directly, the formula can stay the same even when the age changes.
That's the secret to how variables make code flexible.
Several variables together hold information
One variable holds one value.
Use several, and you can store different pieces of information separately, like a name, an age, and a height.
Gather variables like this and you can hold something complex, like information about one person.
Holding information with several variables.
Variables are the most basic ingredient of programming.
How you handle the values inside depends a little on whether they're numbers or text.
In the next lesson we'll cover input and output, putting values into these boxes and showing them, and after that we'll look at the kinds of values.