When introducing variables, it is important to make the distinction between variables in computer science and variables used in mathematics (e.g., algebra). Most of your students probably understand algebraic variables, but they differ from variables used in a programming language in some important ways.
Listed below are three mathematical statements that a middle school or high school student might encounter:
- x – 2 = 4
- x = 6
- x – 6 = 0
These three equations are all valid and mean the same thing mathematically. Namely, x is equal to 6. The second equation is, in a way, the simplest way to express this concept.
In computer science, however, a variable refers to a memory location where data is stored. The value of the variable can be anything whose type matches the type of the variable. For instance, if a variable is designed to store an integer value, it can hold any integer value in a range that extends to the negative and positive limits of the programming language in question. For example, in Python versions 2.x, the regular integer type has 2**31 – 1 (2,147,483,647) as the largest possible positive integer.
A good way to imagine a variable is as a safe deposit box at a bank in which you can put any sum of money. The name of the box remains the same, but the value/contents can change at any given instant in time. The name tells the computer which “box” to use when storing the value.
Hence, x = 6 means that there exists a variable (i.e., a box) x in which a programmer can store integer values and that the value 6 is currently being stored in x.
Now consider the following statement in a mathematical context:
x = x + 1
In math, this statement is false, as there is no number that is equal to one more than itself. If you subtract x from each side, you are left with the statement, “0 = 1”. This cannot be true.
In a computer science context, however, the notation x=x+1 represents an assignment statement and it means that we add 1 to the value of variable x, and then store the result back into x.
The process that occurs is that all variables on the right hand side of the equals sign are replaced by the value that is stored in that variable at the time when the line of code is executed. The right hand side is then evaluated and the result is assigned to the variable, x. For example, if x = 6 when the line above executes, the x on the right hand side will be read as 6, the 6 will be added to 1, and the result (7) will go into the box called x.
Example: Introducing variables using an “unplugged” or hands-on model
An instructor can demonstrate this process by using marbles in a cup. When a variable is created, place a clear plastic cup on a desk and write the name of the variable on the cup with a marker. If the value, 2, is initially assigned to the cup, put two marbles in the cup. When the variable is used further down in the flow of execution, first check how many marbles are in the cup, and make any necessary changes to that number of marbles.