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.
Run the examples
Section titled “Run the examples”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.
Assignment
Section titled “Assignment”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 = 1542print(gene_count)1542Store a sample identifier as a string:
sample_id = "SAMPLE_01"print(sample_id)SAMPLE_01Store a boolean flag:
is_significant = Trueprint(is_significant)TrueVariable names should be descriptive. Use lowercase words joined by _, the convention Python calls snake_case. Avoid single letters except in short loops.
Integers
Section titled “Integers”Integers are whole numbers with no decimal point. They are useful for read counts, chromosome positions, and gene totals.
read_count = 15000print(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
Section titled “Floats”Floats are numbers with a decimal point. They are common for expression values, p-values, and fold changes.
expression_value = 23.45print(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.003log2fc = 2.5print(f"p-value: {pvalue}, log2FC: {log2fc}")p-value: 0.003, log2FC: 2.5Strings
Section titled “Strings”Strings hold text. In bioinformatics you will use them for gene names, chromosome labels, DNA sequences, and file paths.
F-strings
Section titled “F-strings”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 chr17String length
Section titled “String length”The len() function returns the number of characters in a string. This is handy for checking sequence lengths.
print(len(gene_name))5String methods
Section titled “String methods”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())ATGCGATCGACount how many times a base appears in a sequence:
print("ATGCGATCGA".count("G"))3Other helpful string methods include .lower(), .replace(), .startswith(), and .split(). You will see these throughout the course.
Booleans
Section titled “Booleans”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.003is_significant = pvalue < 0.05print(is_significant)TrueCombine multiple conditions with and. This is a common pattern when filtering differential expression results.
log2fc = 2.5passes_filter = is_significant and abs(log2fc) > 1print(passes_filter)TruePython 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 = Noneprint(annotation)NoneUse is to check for None. Do not use ==.
print(annotation is None)TrueOnce you assign a real value, the check returns False:
annotation = "tumor suppressor"print(annotation is None)FalseType checking
Section titled “Type checking”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))Trueprint(isinstance(42, (int, float)))TrueType conversion
Section titled “Type conversion”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)1600Convert an integer to a string:
print(str(42))42Convert a string to a float:
print(float("3.14"))3.14Convert a float to an integer. Python truncates toward zero, dropping the decimal part.
print(int(3.7))3Floating point: why == is the wrong test
Section titled “Floating point: why == is the wrong test”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.30000000000000004FalseThe 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))TrueNumPy provides np.isclose and np.allclose for arrays. Tests can use
pytest.approx to compare an expected value within a tolerance.
Division and rounding
Section titled “Division and rounding”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.57 // 2 = 3-7 // 2 = -4int(-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) = 0round(1.5) = 2round(2.5) = 2This rule avoids always moving exact half cases upward.
Predict before you run
Section titled “Predict before you run”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.
Quick reference
Section titled “Quick reference”| 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 |
Next steps
Section titled “Next steps”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.
Further reading
Section titled “Further reading”-
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.