Variables & Assignment

A variable is a name that has a value associated with it.

You can assign a value to a variable name using the equals sign.

In [1]:
tail_length_mm = 27

On the left hand side of the equals is the name of the variable. On the right hand side is that value that is assigned to it.

The variable name then works just like typing it's value.

In [2]:
tail_length_mm
Out[2]:
27
In [3]:
10 + tail_length_mm * 2
Out[3]:
64

The value of the variable won't change unless you assign a new value to that variable.

The value of one variable can also be assigned to another variable.

In [4]:
focal_tail_length = tail_length_mm
focal_tail_length
Out[4]:
27

Or we can do a calculation with a variable and then assign it to a new variable.

In [5]:
mass_g = 1000
mass_kg = mass_g / 1000
mass_kg
Out[5]:
1
In [6]:
x = 10
y = 2
x_plus_y = x + y
print(x_plus_y)
12

Changing the value assigned to a variable does not change anything that has already happened. It only changes things that happen after the change.

In [7]:
genome_length = 600
half_genome_length = genome_length / 2
genome_length = 1000
print(half_genome_length)
300

We can also use the same variable on both sides of an equals sign. This is conterintuitive from a mathematical perspective as we would never expect to see x = x + 5, but it's perfectly fine in programming.

In [8]:
x = 10
x = x + 5
x
Out[8]:
15

This works because the expression on the right hand side of the equation is evaluated first. Specifically, the order of operations is:

  1. Look up the current value of x
  2. Add 5 to that value
  3. Assign the value resulting from the addition to x

Updating the value of a variable like this is a common paradigm in programming.