Variables

When writing programs, we often want to name values so that we can refer to them later. A name that refers to a value is called a variable.

In [1]:
x = 10

The general form of a variable assignment statement is: «variable» = «expression»

An assignment statement is executed as follows:

  • Evaluate the expression on the right-hand side to produce a value. This value has a memory address.
  • Store that memory address in the variable on the left-hand side. (Create a new variable if it doesn't exist; otherwise just reuse the existing variable.)

We can now retrieve the value that x refers to by typing x in the shell:

In [2]:
x
Out[2]:
10

We computed things like 10 + 5 before. Now we can use variables in place of actual numbers:

In [3]:
x + 5
Out[3]:
15

The code x + 5 is an expression, just like 10 and 10 + 5 are, so we can store the result in a variable:

In [4]:
result = x + 5
In [5]:
result
Out[5]:
15

Variable names must start with a letter or an underscore. They can only include letters, digits, and underscores.

Practice Exercise: Working with Variables

  1. Consider this code:

    j = 7
    
    Write an assignment statement that creates a new variable k that refers to three times j's value.

  2. Consider this code:

    patient_a = 3
    patient_b = 4
    patient_a = 5
    
    After the code above is executed, to which value does patient_a refer?
    After the code above is executed, to which value does patient_b refer?

  3. Consider this code:

    x = 4
    y = x + 2
    x = y + 1
    
    After the code above is executed, to which value does x refer?
    After the code above is executed, to which value does y refer?

Practice Exercise: Solving a problem using variables

Fridericia's Formula for the corrected QT is $$QTc = \frac{QT}{RR^{\frac{1}{3}}}$$

The R-R interval is measured in seconds, and can be ontained using $60/hr$, where hr is the heart rate. Given the hr and qt variables below, and calculate the QTc (corrected QT interval).

In [1]:
hr = 70
qt = 300

The corrected QT interval should be: 315.817979882819 seconds.