Declaring and Initializing Variables
Learn about how variables work and how to name them.
We'll cover the following...
Variables
When writing programs, we continuously work with data. We need a way to keep track of this data we’re using. To do this, we use variables. Let’s look at how this works in the following sections.
Understanding variables
To understand what a variable is, we can start with some code where we assign a value to a variable:
x = 13
Here, we have the value 13
, which is a whole number. In programming, we usually refer to these as integers because they can be both positive and negative. Different programming languages treat integer values differently. Most languages will specify how much memory an integer will use. Let’s assume that this size is 4 bytes, which is a common size used to store an integer value. Remember that one byte is 8 bits and that each bit can be either 0 or 1. With 4 bytes, we have 4 times 8 bits—which is 32 zeros or ones—at our disposal.
To store 13 in the computer’s memory, the programming language will need to reserve enough space—4 bytes, in our case.
Each byte of computer memory has an address. A memory address works like a street address; it’s used to help us navigate to the correct location:
In our example, 4 bytes that aren’t occupied by something else need to be located. These bytes need to be in continuous order.
The address of the first byte in this sequence is of interest to us. The programming language knows that we’re storing an integer value at this location, and it knows how many bytes an integer occupies, so the first address is enough to locate this ...