Skip to content

Variables & Data Types

Python has a small set of built-in data types that cover most everyday needs. This page walks through each one with examples drawn from bioinformatics. By the end you will know how to create variables, check their types, and convert between types.

Use a Python project managed by uv. If you need to create one, follow the project setup instructions first. Save the Python blocks in a file named variables.py, in page order, and run uv run python variables.py from the project directory in your terminal.

Copy the Python code, not the output blocks underneath it. Those blocks show what the example prints. A terminal command starts a program; the code inside variables.py runs inside Python. These examples use Python’s standard library and need no third-party package.

A variable is a name that points to a value. You create one with the = operator.

Store a gene count as an integer:

gene_count = 1542
print(gene_count)
1542

Store a sample identifier as a string:

sample_id = "SAMPLE_01"
print(sample_id)
SAMPLE_01

Store a boolean flag:

is_significant = True
print(is_significant)
True

Variable names should be descriptive. Use lowercase words joined by _, the convention Python calls snake_case. Avoid single letters except in short loops.

Integers are whole numbers with no decimal point. They are useful for read counts, chromosome positions, and gene totals.

read_count = 15000
print(type(read_count))
<class 'int'>

Python integers expand as their value grows. They do not overflow at a fixed machine-word boundary, but their size remains limited by available memory.

Floats are numbers with a decimal point. They are common for expression values, p-values, and fold changes.

expression_value = 23.45
print(type(expression_value))
<class 'float'>

You will often work with multiple float variables together. F-strings make it easy to print them in a readable format.

pvalue = 0.003
log2fc = 2.5
print(f"p-value: {pvalue}, log2FC: {log2fc}")
p-value: 0.003, log2FC: 2.5

Strings hold text. In bioinformatics you will use them for gene names, chromosome labels, DNA sequences, and file paths.

F-strings let you embed variables directly inside a string. Prefix the string with f and put variables in curly braces.

gene_name = "BRCA1"
chromosome = "chr17"
print(f"Gene {gene_name} is on {chromosome}")
Gene BRCA1 is on chr17

The len() function returns the number of characters in a string. This is handy for checking sequence lengths.

print(len(gene_name))
5

Strings come with many built-in methods. Two useful ones for bioinformatics are .upper() and .count().

Convert a lowercase DNA sequence to uppercase:

sequence = "atgcgatcga"
print(sequence.upper())
ATGCGATCGA

Count how many times a base appears in a sequence:

print("ATGCGATCGA".count("G"))
3

Other helpful string methods include .lower(), .replace(), .startswith(), and .split(). You will see these throughout the course.

Booleans are either True or False. They result from comparisons and logical operations.

Check whether a p-value is below a significance threshold:

pvalue = 0.003
is_significant = pvalue < 0.05
print(is_significant)
True

Combine multiple conditions with and. This is a common pattern when filtering differential expression results.

log2fc = 2.5
passes_filter = is_significant and abs(log2fc) > 1
print(passes_filter)
True

Python also supports or and not for combining boolean values.

None represents the absence of a value. A function without an explicit return value returns None. An unassigned name is different: reading it raises NameError.

annotation = None
print(annotation)
None

Use is to check for None. Do not use ==.

print(annotation is None)
True

Once you assign a real value, the check returns False:

annotation = "tumor suppressor"
print(annotation is None)
False

Use type() to see what data type a value has.

print(type(gene_name))
<class 'str'>
print(type(42))
<class 'int'>
print(type(3.14))
<class 'float'>
print(type(True))
<class 'bool'>

Use isinstance() when you need to check if a value belongs to a specific type. This function also accepts a tuple of types.

print(isinstance(gene_name, str))
True
print(isinstance(42, (int, float)))
True

Sometimes you need to convert a value from one type to another. Python provides built-in functions for this.

Convert a string to an integer. This is common when reading count data from text files.

count_string = "1500"
count_number = int(count_string)
print(count_number + 100)
1600

Convert an integer to a string:

print(str(42))
42

Convert a string to a float:

print(float("3.14"))
3.14

Convert a float to an integer. Python truncates toward zero, dropping the decimal part.

print(int(3.7))
3

A float is a binary approximation. 0.1 has no exact binary form, so arithmetic on it does not land where you expect.

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
0.30000000000000004
False

The printed approximation and the equality test answer different questions. Use a tolerance when you compare computed values. Python’s floating point tutorial explains this representation and the role of math.isclose().

import math
print(math.isclose(0.1 + 0.2, 0.3))
True

NumPy provides np.isclose and np.allclose for arrays. Tests can use pytest.approx to compare an expected value within a tolerance.

print(f"7 / 2 = {7 / 2}")
print(f"7 // 2 = {7 // 2}")
print(f"-7 // 2 = {-7 // 2}")
print(f"int(-3.7) = {int(-3.7)}; round(-3.7) = {round(-3.7)}")
7 / 2 = 3.5
7 // 2 = 3
-7 // 2 = -4
int(-3.7) = -3; round(-3.7) = -4

// floors toward negative infinity; int() truncates toward zero. They disagree on negatives, which is a real source of off-by-one bugs in index arithmetic.

Python’s round() is banker’s rounding: halves go to the even number.

for value in (0.5, 1.5, 2.5):
print(f"round({value}) = {round(value)}")
round(0.5) = 0
round(1.5) = 2
round(2.5) = 2

This rule avoids always moving exact half cases upward.

A CSV field contains the text "0", another contains "0.0", and a third has no recorded value and becomes None. Predict which fields an integer conversion accepts, which values count as false in a condition, and which field represents a missing measurement. Explain why testing the original text as a Boolean does not determine whether its numerical value is zero.

Open the type explanation.

The integer conversion accepts "0". It rejects "0.0" because that string uses floating-point syntax, and it rejects None because absence is not a number. Both original strings are nonempty, so both are true in a condition. The converted integer zero is false, as is None, but only None represents the missing measurement in this contract. Use an explicit missing-value check before conversion, then select the conversion required by the data specification.

Type Example Use case
int 1542 Read counts, gene totals
float 0.003 P-values, fold changes
str "BRCA1" Gene names, sequences, file paths
bool True Significance flags, filters
None None Missing or unset values

You now know how to store and inspect individual values. Real datasets contain many values grouped together. Head to Data Structures to learn about lists, dictionaries, tuples, and sets.

  • Python tutorial: floating-point arithmetic

    The tutorial explains binary representation error and why decimal expressions can fail exact equality. It compares rounding with math.isclose and describes the limits of displayed precision.