← All concepts

Lecture 1

Variables, print() and f-strings

A variable is a name for a value. print() shows values, and f-strings drop them into text.

A name for a value

Use a single = to store a value under a name. Assigning again replaces the old value: a variable holds one value at a time, and each line uses the value from the line before.

cells = 120
cells = cells + 30
print(cells)

Output

150

Good names

Names may contain letters, digits and underscores, but cannot start with a digit or contain spaces or hyphens. They are case-sensitive: Gene and gene are different names.

print() and f-strings

print() shows each item it is given, separated by a space. An f-string — text with an f in front — replaces every {name} with that variable's value. Without the f, the braces are printed as they are.

gene = "TP53"
length = 393
print("Gene:", gene)
print(f"{gene} has {length} amino acids")
print("{gene} has {length} amino acids")

Output

Gene: TP53
TP53 has 393 amino acids
{gene} has {length} amino acids

Going further

For the advanced questions.

Formatting numbers

Inside the braces you can put a whole expression, and after a colon a format: :.2f shows two decimal places, :.0f none.

ratio = 2 / 3
print(f"{ratio:.2f}")
print(f"{ratio * 100:.0f} percent")

Output

0.67
67 percent

Copying a value, not a link

b = a copies the value a has at that moment. Changing a afterwards does not change b. Shortcuts such as += update a variable using its own value.

a = 3
b = a
a += 1
print(a, b)

Output

4 3