Python for Biologists

Lesson 2 of 14 · 10 min

Variables and Data Types

A program constantly needs to store pieces of data so it can use them again later. In Python you do this with a variable, which is a name that points to a value; you create one with the assignment operator, a single equals sign, with the name on the left and the value on the right. This is not the equals of mathematics: it means take the value on the right and store it under the name on the left.

python
# Store a value in a variable using =
organism = "Escherichia coli"
gene_count = 4400

# print shows the value on the screen; text after # is a comment Python ignores
print(organism)
print(gene_count)
Escherichia coli
4400

Four core data types

Python sorts every value into a type, and four are essential to start with. An int is a whole number, a float is a number with a decimal point, a str (short for string) is text wrapped in quotation marks, and a bool (short for boolean) is either True or False. The built-in type function reports the type of any value, printing it as <class '...'>, where class simply means category.

python
count = 20            # int: a whole number
temperature = 37.0    # float: a number with a decimal point
name = "Homo sapiens" # str: text wrapped in quotation marks
is_pathogen = False   # bool: either True or False

print(type(count))
print(type(temperature))
print(type(name))
print(type(is_pathogen))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
python
# Basic arithmetic with two whole numbers
a = 8
b = 3

print(a + b)   # addition
print(a - b)   # subtraction
print(a * b)   # multiplication
print(a / b)   # division
print(a ** b)  # exponent: a raised to the power of b
11
5
24
2.6666666666666665
512
python
# Store biological data in clearly named variables
dna_sequence = "ATGGCCTAA"
organism_name = "Saccharomyces cerevisiae"

print(organism_name)
print(dna_sequence)
print(type(dna_sequence))
Saccharomyces cerevisiae
ATGGCCTAA
<class 'str'>

Try it yourself: Create a variable called codon and set it to the string "AUG", the start codon in messenger RNA. Then create a variable called weight_kg set to 0.5. Finally, print type(codon) and type(weight_kg). Predict what Python will print for each before you run it, then check whether you were right.