Variables#

In earlier sheets, we saw that Python can be used as a calculator. One feature that distinguishes it from a (basic) calculator is the ability to remember values in variables.

Suppose we are going through a recipe book which is written using imperial units, and would like to convert all of the measurements into metric units. One of the conversions we would have to do is to replace pounds with grams. In the UK, one pound is precisely defined to be 0.45359237 kg. It would be annoying if we had to type in that number every time we do a conversion, and would likely lead to mistakes.

This is where variables come in. We can assign the value of \(0.45359237\) to a variable, then use this variable in place of the number.

pounds_to_kg = 0.45359237

The = in the above cell means that we are assigning the value \(0.45359237\) to the variable pounds_to_kg.

You should not expect Python variables to behave exactly the same way as mathematical variables, though they are similar concepts. One way of thinking about Python variables are that they are just “labels” for an object. Here we have made a label called pounds_to_kg, which is attached to a single number. Whenever we use the name of a variable in an expression, Python replaces it with whatever object the label is attached to.

We can output the contents of a variable by just writing its name as the last thing in a cell:

pounds_to_kg
0.45359237

Now if the recipe book calls for \(3.6\) pounds of flour, we can easily calculate the number of kilograms:

flour_in_pounds = 3.6

flour_in_kg = pounds_to_kg * flour_in_pounds

flour_in_kg
1.632932532

Reassigning variables#

Continuing the analogy between labels and variables, we can replace the value of a variable, much like attaching the label to a new object.

For example, if our recipe book the recipe book was written in France during the 18th century, we would probably want to use a different conversion factor for the pound (corresponding to the livre de Paris):

pounds_to_kg = 0.4895

In some programming languages, changing pounds_to_kg would change any other variables that were initially computed using the variable pounds_to_kg. This is not the case in Python:

flour_in_kg
1.632932532

This is still the same value of flour_in_kg that we saw above!

The ability to re-assign variables can lead to some code which looks very strange from a mathematical point of view!

a = 2
a = a * 4 + 1

a
9

The line a = a * 4 + 1 looks mathematically strange, but it really just means “re-assign a to mean the current value of a, multiplied by four, plus one”. Roughly speaking, the a on the left-hand side of the = means “the label a”, and the a on the right-hand side means “the thing labelled by a”.

Viewing variables#

The simplest way to find the investigate the value of a variable is to simply write it as the last line of a cell:

a
9

You can also find a list of all of the variables you have defined by writing %whos. This might display a number of variables that exist “in the background” as well as the ones that you have explicitly defined.

%whos
Variable          Type     Data/Info
------------------------------------
a                 int      9
flour_in_kg       float    1.632932532
flour_in_pounds   float    3.6
pounds_to_kg      float    0.4895

Finally, you can open the “Variable Inspector” if that extension is available, via a button on the menu bar which looks like a target symbol. It will appear as a floating window detailing all of your variables.

Variable names#

There are three “core” rules for Python variable names. You don’t need to memorise these - you will learn them quickly!

  1. Variable names can only contain letters, numbers, and underscores (my_1st_variable)

  2. Variable names cannot start with a number (no 1st_variable)

  3. Variable names are case-sensitive (so a and A are different variable names)

Beyond these, there are some useful conventions:

  1. For multi-word variable names, use underscores between the words (the snake_case convention), or start each word other than the first with a capital letter (the camelCase convention).

  2. Variable names should be descriptive: number_of_loops is better than x

  3. Do not use names that Python already uses, like sum or list. You can do so in some cases, but do not. Such names will be highlighted in green in your Jupyter Notebook.

Optional: Multiple labels for one object#

There is another way that variables are like labels: one object can have multiple labels, and in Python multiple variables can refer to the same thing:

from mobilechelonian import Turtle

terry = Turtle()   # make a turtle called terry
tina  = terry      # now tina stores the same object as terry

# calling the commands on either tina or terry will affect the same turtle,
# because there is only one turtle!
tina.forward(100)
terry.left(45)
tina.forward(100)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Input In [9], in <cell line: 1>()
----> 1 from mobilechelonian import Turtle
      3 terry = Turtle()   # make a turtle called terry
      4 tina  = terry      # now tina stores the same object as terry

ModuleNotFoundError: No module named 'mobilechelonian'

The real story is this: variables simply store an “address” which tells Python where to find the object in the computer’s memory. In the example above, there is one turtle stored in memory, which does not even know about the variables terry or tina. Whenever we use the name terry or tina Python looks up this object using the address stored in terry or tina and performs the commands on that object.