What Is a Variable?

Most schools have lockers for students to keep their books in. Variables are a lot like lockers: variables are places in which computers keep things. Computers need containers in which to keep numbers, text, and other information so that later they can make decisions. The code tells the computer when to look in these lockers and what to look for.

“Hey, computer… get my science book, because it is fifth hour!”

Here are some examples of things computers might store in variables.

Weather computer example:

  • Variables: temperature, time, day of the week, amount of rainfall, etc.

Sports computer example:

  • Variables: touchdowns, player names, home runs, bases stolen, birdies, etc.

Clothing computer example:

  • Variables: what is dirty, what is clean, what I want to buy, number of shoes, number of socks, etc.

Each variable holds a specific type of information. The first time you use a variable, you set its type. From that point on, you can store only information of that type in that variable.

Types of variables

A number variable holds numeric data. Examples: a person’s age, a player’s score, the year

A string variable holds a string of alphanumeric characters. Examples: a person’s name, a password, the day of the week

A Boolean variable has only two possible values: true or false. Examples: Is it daytime? Is the game over?

In MakeCode, a position variable is a special kind of variable that holds three numbers that describe a specific location in three-dimensional space. These numbers are called the X, Y, and Z coordinates. You probably remember this from Lesson 3!

Values of variables

Here are some more examples of variables.

Variable Name Value
Cats 2
Dogs 5
Greeting “hello!”
HousePosition (12, 4, -36)

Variable names can be used in place of values. Given the variables above, you could make the following statements:

Cats + Dogs = 7
Say Greeting
Teleport to HousePosition

You can change the value of a variable:

Set Cats to Dogs + 4
Cats = 9

What is the type of each of these variables?

  • Cats
  • Dogs
  • Greeting
  • HousePosition