ubuntu2004
Numerical variables
What are variables and why do we need them?
How many "f"s are there in this sentence?
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
:
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
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
To print out its type we use
Run the code below to see the output.
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 count
changes.
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.
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
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:
Here's another, shorthand, way of doing this using the increment operator +=
:
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:
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:
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:
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.
Run the code to look at the output. Notice that the result has many decimal places.
Use
round()
to round the result to 1dp (see the last Notebook if you have forgotten how to do this).
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.
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:
Or if we need to use double quotes in an f-string, the f-string should start and end with single quotes:
If you get this wrong, you'll just get a Syntax Error.
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.
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()
andtype()
.Variable names cannot start with a number.
For single-character names, avoid using
l
,O
orI
(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
, anddna_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.