Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
10327 views
ubuntu2004
Kernel: Python 3 (system-wide)

Numerical variables

What are variables and why do we need them?

How many "f"s are there in this sentence?

The embryo of Festuca fusca,
a native plant species of
Old-World countries, is almost
half the full length of its grain.

How many did you find? The answer is at the bottom of this Notebook.

What we want to do is write some code to answer the same question. But first let's think about how you did this task by hand as that will help us write the code.

What you did was work your way along the sentence and add 1 to a tally every time you encountered an "f". In your head (or more specifically the short-term memory of your pre-frontal cortex) your tally started from zero, you read along the sentence until you found an "f" and you added one to your tally. Alternatively, you may have used your fingers as a way to keep a tally or written it down.

When writing a program to perform a task like the one above, we need to store information in the computer's memory (made of transistors rather than neurons) so that it can be recalled and changed later in the program.

A piece of information stored in computer memory is called a variable.

Properties of Python variables

A Python variable has three properties: a name, a type and a value.

Here is an example of a Python statement assigning the value of 3.7 to the variable with name x:

x = 3.7

The variable's name is x, its value is 3.7 and its type is a float (because it has a decimal point).

Here is another example

count = 0

In this example the variable's name is count, its value is 0 and its type is an integer (because it is a number without a decimal point).

In Python we can decide what to call our variables as long as we don't use words already reserved in Python. There is advice on picking good variable names later in this Notebook.

Printing the value and type of a variable

In the code cell below the variable count is assigned the value of 0, an integer.

To print out its value we use

print( count )

To print out its type we use

print( type( count ) )

Run the code below to see the output.

count = 999.0 # Assign the value of 0 to the variable called count. print( count ) # Print the value of count. print( type(count) ) # Print the type of count.
999.0 <class 'float'>

The value of a variable can change

The whole point of a variable is that its value can change - hence the name "variable".

Run the following code to see how how the value of the variable countchanges.

count = 0 # Assign the value of 0 to the variable called count. print( count ) count = 1 # Change the value of count to 1. print( count )
0 1

When we were counting the number of "f"s above we kept a tally in our heads; each time we found an "f" we increased our tally by 1. How do we write incrementing a tally in Python?

Here's one way we might first think it could be done using the variable called count to keep a tally.

Look at the code below, think what it does then run it to see the result.
count = 0 # Assign 0 to count. print(count) count = count + 1 # Add 1 to the value of count. print(count)
0 1

Why does it not work? Why isn't count equal to 1 when it is printed the second time?

To answer that we need to know a little about how a computer works. When we write

count + 1

Python copies the value of count in memory, which is 0, into the central processing unit, or CPU for short (blue arrow pointing from memory to CPU in this figure). The CPU and adds 1 to it resulting in a value of 1 in the CPU.

But, at this point, the code does not update the value of count stored in memory, which is still 0.

In order to update the value of count in memory to 1 (blue arrow pointing from CPU to memory), we need reassign the result of the calculation back to the variable count like so:

count = count + 1
Run the following code to see how it works.
count = 0 # Assign 0 to count. print(count) count = count + 1 # Add 1 to the value of count in the CPU and reassign the result to count in memory. print(count)
0 1

Here's another, shorthand, way of doing this using the increment operator +=:

count = 0 # Assign 0 to count. print(count) count += 1 # Increment the value of count by 1. print(count)
0 1

A variable can be incremented or decremented by any number, not just 1. For example, say we were counting the cumulative total number of covid19 cases each day. We might write something like this:

cases = 125 print( cases ) cases += 239 print( cases )
125 364

Variables can be used in arithmetic

In the last Notebook we learned how to do basic arithmetic using numbers in Python. We can do exactly the same with variables.

For example, say we wanted to find the density of worms in a garden, that is, we want to find the average number of worms per square metre. We would first measure the area of the garden, say its 168m2. Let's assign that to a variable called garden_area like so:

garden_area = 168

Then we count the number of worms in the whole garden, say its 1042. Let's assign that to a variable called number_of_worms like so:

number_of_worms = 1042

Now, of course, we could simply type 1042 / 168 into a calculator and get the answer 6.2 worms/m2 (rounded to 1 decimal place, or 1dp for short). But with code we can store the result in another variable for later use (perhaps if we are comparing worm density in many gardens of different soil types and wanted to plot the results in a bar chart).

Let's save the worm density in a variable called worms_per_sqm and print it. The following code shows how to do this.

  1. Run the code to look at the output. Notice that the result has many decimal places.

  2. Use round() to round the result to 1dp (see the last Notebook if you have forgotten how to do this).

garden_area = 168 number_of_worms = 1042 worms_per_sqm = round(number_of_worms / garden_area, 5) print(worms_per_sqm)
6.20238

Python substitutes the values of the variables number_of_worms and garden_area into the equation and then assigns the result to the variable worms_per_sqm.

All of the arithmetic we can do with numbers we can also do with numerical variables. There are more examples below for you to try.

Make your output meaningful with f-strings

In the above example, when we printed out the value of the variable worms_per_sqm to 1dp, we got 6.2. But we want to add some context to our output, and, more importantly, add some units: 6.2 what?

We can format our output with something called a formatted string or f-string for short. The following code gives an example.

Run the code to look at the output.

print( f'Worm density is {worms_per_sqm:.4f} worms/m^2' )
Worm density is 6.2024 worms/m^2

The f in front of the single quote tells Python that what follows is an f-string. The variable name worms_per_sqm is placed inside a pair of curly brackets {}. This tells Python to replace the variable name worms_per_sqm with its value 6.2023809523809526. The notation :.1f tells Python to format the value to 1 decimal place.

f-strings are a great way to format output. We'll encounter them again later.

If we need to use an apostrophe inside an f-string, the f-string should start and end with double quotes:

print( "Darwin's Dangerous Idea" )

Or if we need to use double quotes in an f-string, the f-string should start and end with single quotes:

print( 'Say, "Hello, world"' )

If you get this wrong, you'll just get a Syntax Error.

Look at the following code to see how it's done.
print( "Darwin's Dangerous Idea" ) print( 'Say, "Hello, world"' )
Darwin's Dangerous Idea Say, "Hello, world"

What should I call my variable?

Variables should generally be lowercase with words separated by underscores as necessary to improve readability. Some Python coders prefer mixedCase, where capital letters denote word boundaries.

It is helpful if variable names mean something, that is, choose names that help you remember why you created the variable in the first place and what value it contains. The following three blocks of code produce the same results when run by the computer, but vary in how easy they are to understand for a human reader.

# The variable names in this example don't tell us anything useful about what they contain. a = 670 b = 100 c = a // b print(c)
6
# These variable names are obscure and irrelevant and therefore unhelpful, but the mathematical operation is identical. longjing = 670 london = 100 lemur = longjing / london print(lemur)
6.7
# These variable names make it clear that we must be calculating a concentration. # This is much more helpful when we revisit our code at a later time. milligrams = 670 millilitres = 100 concentration = milligrams / millilitres print(concentration)
6.7

Variable naming guidelines

We can call our variables almost anything we like, although it is useful to follow the guide below:

  • Do not use any of Python's keywords, i.e., words that already have a meaning in Python (see table below). Also avoid words that can be confused with these keywords (such as capitalized equivalents e.g., Yield), although doing so would not raise an error.

  • Avoid using function names as variable names. Later in this course we will learn more about functions. So far we have only used print() and type().

  • Variable names cannot start with a number.

  • For single-character names, avoid using l, O or I (lowercase el, uppercase oh and eye), as these may be indistinguishable from the numbers 1 or 0 or may be mixed up with themselves.

  • Variable names are case-sensitive, so dna_seq, dna_SEQ, and dna_Seq are all separate variables. Although technically we could use all of these combinations, it would be confusing both to the coder and anyone reading or editing the code.

  • Avoid names that are too wordy (e.g., number_of_amino_acid_residues_in_protein_motif) but do try to make it obvious what they are from the name (e.g., motif_residue_count).

Reserved keywords in Python

Do not use any of these reserved words as variable names.

False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

Exercise Notebook

Next Notebook

How many f's? The answer is 7.