Module 0-2: Variables

A variable in a programming language is a little different than something like a variable in algebra. In a programming language, a variable is a name that you assign a piece of data. You can change a variable's value to anything else afterwards. You can use a variable in place of data. You can make as many variables as you want.

Let's make a simple variable to demonstrate. In Python, the syntax for making a variable is to state the name of your variable, an equals sign, and then the data.

Run this and the number 4 will be printed to the console. Pretty simple, right?

You can also update

a
's value by assigning a new value. There are two ways of doing this. First, you can directly assign a new value; for example, we can say
a = 6
to change
a
's value to 6. Or, you can base the
a
's new value off of
a
's current value. For example, we can say
a = a - 1
, which takes
a
's current value, subtracts it by 1, and then saves it back into
a
. What would the following code print to the console?

The answer is 5.

a
starts off at 4, then is changed to 6, and then we subtract 1 from
a
.

Why would we use variables? It's a very simple concept, but it is essential for a robust program. Variables allow us to track changes to data over a program's run time, giving us the potential to make programs do different things depending on the current state of data.