Where do we store values?
Last time, we said code is telling a computer what to do, in order. But where do we put the values those commands handle? A box that stores a value under a name, the variable, is up next.
To reuse a value you wrote once
As you calculate,
you often reuse a value.
Your age, for example.
To say "use this year's age for this,
and for that too,"
you have to store that age
somewhere.
Otherwise you'd repeat it every time.
What if you don't store the value?
So what you need
is to give the value a name
and store it.
Once stored,
you can take it out again anytime
by that name.
This storing box is called a variable.
A variable is a labeled box
Draw a variable as a picture
and it's a single box.
Put a label on the box,
and a value inside.
"Put 25 into the box called age."
Like this.
Set a name and value
and make a box.
Set a name and a value.
The label is what you call the box by,
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 get the value.
The box stays, only the value changes
The real use of a variable is here.
The value in the box
can be changed anytime.
Leave the label as is,
and just swap the contents.
Think of a game score.
Into one box called score,
numbers keep changing as they go in.
Keep the box name, just change the value.
The name "score" didn't change,
but the value inside kept changing, right?
Because it can change,
it's called a variable.
Thanks to this, code
behaves differently by situation.
Variables can do math together
One more good thing about variables.
You can calculate with names
instead of values.
"Next year's age is age plus 1."
Write this,
and whatever the age is,
you always get a value one greater.
Change the age with the slider.
Change the age and the result follows.
Because you calculate with a name
instead of writing the value directly,
even if the age changes,
you can leave the formula as is.
This is the secret to how variables
make code flexible.
Many variables together hold information
One variable, one value.
So what if you use several?
Like name, age, height,
you can hold many pieces of information separately.
When variables gather like this,
you can hold complex things too,
like one person's information.
Holding information with several variables.
Variables are programming's
most basic material.
Depending on whether the values held here
are numbers or letters,
how you handle them differs a little.
Next time we'll look at
the kinds of these values.