Mark Redd

9 - Variables and Memory

Now we will introduce some concepts that make Python far more powerful. You have the ability to store things in computer memory and the following exercise will demonstrate how it works.

# vars_and_mem.py

# equals sign ( = ) is the assignment operator
# it says: assign whatever is on the right 
# to the name on the left
first_text = "Here is some text!"
more_text = "This is another string of text."

print("{} {}".format(first_text, more_text))

# You can print numbers too! Here are some
random_integer_1 = 1
random_integer_2 = 23
random_number = 25.34

# notice the format of the code
# you can do this any time you have a
# comma separated list
# we also reuse the variable "first text" 
print("{} {} {} {}".format(
    first_text, 
    random_integer_1,
    random_integer_2,
    random_number
))

# now lets do the same thing but assign these 
# names to new values!
first_text = "Here are some more numbers"
random_integer_1 = 34
random_integer_2 = 203
random_number = 3.14159265

# notice how this print statement does the same
# thing as the last print statement
print(
    message, 
    random_integer_1, 
    random_integer_2,
    random_number
)

Here is what should happen

(If needed, see Section 4 to review how to run a script.)

$ python vars_and_mem.py
Here is some text! This is another string of text.
Here is some text! 1 23 25.34
Here are some more numbers 34 203 3.14159265
$

You can see that each name that is assigned a value can be used multiple times and refers to the same value that gets stored in memory. This name is called a variable. Here is how the computer works with variables.

Computer Bare Essentials

I want to begin here by saying a few things about computers that hopefully will help you understand them better.

Computers, including those that run everything from your desktop to your phone to your car, basically only do 3 things:

  1. Store numbers as 1s and 0s in different places
  2. Move those 1s and 0s between the different places
  3. Compare and combine those 1s and 0s mathematically (e.g. addition and subtraction)

Of course, computers can do these things at blinding speeds and can be endlessly combined to do all sorts of complex things but these three basics make up all of computing. The programs we have been writing so far do just those things but the details of how this is done is hidden from you but don’t be fooled! Nothing more than those three things is happening at any time.

Storing Information

One of the most important things you can learn is how memory works on a computer. Storing 1s and 0s is an essential ability for a computer to function.

For now, you need to understand that there are three basic parts to the computer that we interact with constantly. They are:

  1. The Central Processing Unit (CPU): every instruction in the code gets executed here.
  2. The Random Access Memory (RAM, or volatile memory): relevant program information is stored here as your program runs. As soon as your program stops running, all the information you have in RAM is erased.
  3. The persistent memory: like the RAM, but the information you write here stays until you actively erase it (depending on your hardware). Your program gets stored here and is loaded into RAM to actually run. The persistent memory is generally contained on a drive of some sort (e.g a hard disk drive (HDD) or a solid-state drive (SSD)). We will be doing more with the persistent memory in a later section.

Using RAM

The RAM is where your variables are stored. You can think of the RAM as a large set of P.O. boxes in a vast post office. Each P.O. box has a number associated with it called an address. When you run code like

x = 23

you are executing the following:

Anytime x is referenced after that command, the computer looks up the address associated with ‘x’ and goes directly to the ‘box’ with that address and replaces ‘x’ with whatever is in that ‘box’.

Type, ID and Value

The python interpreter will illustrate this better. Go to your terminal and enter python to start the interpreter.

$ python
Python X.X.X ...
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Run the following commands:

>>> x = 23
>>> type(x)
<class 'int'>
>>> id(x)
140737371887328
>>> x
23
>>> exit()

type , id and exit are other built-in functions like print that provide some useful information about x.

type spits out the type of variable between its parentheses (in this case, an integer or int as given in the interpreter). id spits out the “address” of the variable in the RAM (NOTE: Depending on the Python implementation you are using, this may or may not be the literal address in memory but is always unique to the chunk of memory being used, hence its id or identification). This address will likely be different for every time you start the Python interpreter. Entering the name of the variable simply prints its value and exit() simply exits the program.

You should know at this point that every variable has these three things, namely, a type, ID, and value. This may not be of any consequence right now but it will matter more and more as we go along.

Naming Variables

As a programmer you will have to give names to your variables. There are certain rules for naming variables but, within those rules, you can make up any name you want for any variable. However, the guidelines below will help you make smart choices about how you name variables.

Naming Rules in Python

Python follows some rules on what a valid variable name can be. The rules are as follows:

Reserved Words in Python        
False None True and as
assert async await break class
continue def del elif else
except finally for from global
if import in is lambda
nonlocal not or pass raise
return try while with yield

For a complete explanation of naming, see the section in PEP 8.

Naming Conventions and Guidelines

Within the limits of these rules, you can call your variables any name you want and make them as long or as short as you want. However, there are some conventions you should stick to you make your code better. The following conventions will help make your code easier to write and fix when something goes wrong. (And trust me, something always goes wrong.):

Any good programmer knows that the majority of the time spent coding is actually spent reading and not writing. Python makes it easy for you to write readable code and the first step of writing readable code is to use good variable names.

Hone Your Skills

Advanced Mastery