Tutorial 0c: An introduction to Python syntax and plotting

© 2018 Griffin Chure and Suzy Beeler, modified by Tom Röschinger, 2021. This work is licensed under a Creative Commons Attribution License CC-BY 4.0. All code contained herein is licensed under an MIT license

In this tutorial, we will learn some of the basics of programming in Python. While this will all become muscle memory, it's useful to keep this as a reference. To follow along with this tutorial, launch a Jupyter notebook as described in tutorial 0b and type along as we go into the code cells.

Basic shell commands

In tutorial 0b, you learned how to launch a Jupyter notebook from a terminal. Having knowledge of some basic UNIX command line skills, such as moving between directories, listing files in a given directory, and making new directories, is imperative to becoming a computational scientist. Please see this wonderful tutorial by Justin Bois for a primer on using the command line. Briefly, you will only need to know three commands.

  1. cd - "Change directories". By typing this command, you will be able to move from where you currently are to another folder. You can do this by specifically typing a path, such as cd /Users/sbeeler/bootcamp. You can also move relative to where you currently are by using some shorthand notation. Typing cd .. will move you up one directory, cd ../.. will move you up two directories, and cd ~/ will move you to your home directory.

  2. ls - "List files and directories". Typing this command in your terminal will list all files and directories in your current working directory.

  3. mkdir - "Make directory". This is useful for making new directories on your computer without having to open Finder or Windows Explorer. For example, I can make a data folder in my bootcamp root directory by typing mkdir data. I could make another folder called good_data two directories up from my current folder by typing mkdir ../../good_data.

With these three commands memorized, you should be able to navigate around your computer without leaving the terminal.

Hello, world

As is typical when learning any programming language, we'll start by making our computer speak to us. We'll do this by using one of the many standard functions in Python, the print function.

In the above code, we called the print function and passed the text Hello, world. surrounded by single quotation marks ''. The text was passed as an argument to the print function by placing it in the parentheses. The quotation marks determined the type of the argument to be text, known as a string. While we used single quotations in the above code, we could also use double quotations "". These are exchangeable in Python.

While our 'Hello, world.' is a string, this function can also be used to print other types such as integers (int), decimals (float), and True/False (bool) by passing them as arguments to the print function.

In the above code, it would be nice to be able to add a comment about what the type of each variable is that we are printing, but we don't want this comment to be interpreted by Python. By adding a pound symbol (#) before a line of code, we can force Python to ignore it.

We see that we get the same result. Comments are essential for writing good code. Code should be easily understandable, which can be achieved by both using comments and simpler syntax. This also makes debugging a lot easier.

Basic math


The crux of scientific programming is the ability to perform mathematical operations. Python can do a variety of simple mathematical functions by default.

Everything looks good, but what happened at the end? In Python, you exponentiate terms using a double asterisk (**) and not a caret (^). The caret executes a bitwise operation which is completely different than exponentiation.

Note that the all mathematical operations other than addition (+) can only be done on ints, floats, or bool. The addition operator can be performed on strings too! Let's say we want to stitch together two components of a sequence together.

While all of these operations are simple, we would like some way in which can store a number for further use. We can do this by assigning the output of an operation to a variable.

We can call methods on some data types in Python. For example, we can convert our stitched string into all upper or lower case using the upper() or lower() method.

We can also count the occurrences of a given character in a string by using the count() method.

Lists and tuples

So far, we've learned about floats, ints, bools, and strings as well as how to assign them to variables. But what about when we want to work with a series of these kinds of values? There are a few ways in which we can do this $-$ lists (values within brackets []), tuples (values within parenthesis ()), and arrays (which we'll learn about in the next section).

Note that lists and tuples can have mixed types. Once we have a list or a tuple, we can extract a single value or a range of values by indexing.

To get the first value of the list, I started with zero. In Python, indexing begins at 0. This is different than in other programming languages such as MATLAB and Julia in which indexing begins at 1.

So what exactly is the difference between tuples and lists? Lists are mutable. Tuples are not. This means once a value in a tuple is set in place, it can't be changed without redefining the tuple. Let's demonstrate this by trying to change the first value of our example_list and example_tuple.

Python yelled at us and told is that we cannot reassign a current value in a tuple. This is a very important point. For example, if you want to have some process output a series of values you don't want to be changed, put them in a tuple. Otherwise, put them in a list or an array.

Lists are mutable, but we have to be careful with performing arithmetic operations on them. For example, the operators +,-, **, and / will give you errors. However, the * operator will concatenate a list with itself.

So how do we do more complicated mathematical operations on a series of numbers? How can I multiply each element of an array by five? How do I take the exponential of each element? How do I perform a dot product between two series? To perform such tasks, we will have to import another Python module, NumPy.

Importing modules and working with NumPy

When you open a Python interpreter or run a script, you are only loading the 'standard' Python packages. This means that you are not loading everything you could possibly want, but only the packages you need to perform the task. To perform more elaborate computation in Python, we will need to import an external module called NumPy.

Whenever you write a Python script, you should always import the modules you will need at the very beginning. That way, all of the required packages will be loaded and ready to go when you start loading them, and makes the code easier to read.

Let's talk about the syntax of the above line. I told the Python interpreter that it should import the module called numpy and give it the alias of np. This means whenever I have to call a Numpy associated function, I can do so by typing np.function_name instead of numpy.function_name. The alias can be whatever you would like it to be, but you should stick by the community standards so your code is clear to everyone who is trying to figure out what you are doing. For example, the alias for pandas commonly chosen to be pd.

Numpy is the premier numerical computing module for Python. With it, we have myriad functions for peforming numerical operations.

With numpy comes a new data type called numpy arrays. These are series of values which are mutable (just like lists) which cannot have a mixed data type (unlike lists and tuples). We can also perform mathematical operations on arrays.

Numpy arrays are not limited to being one-dimensional. We can create n-dimensional numpy arrays with ease.

We can even make numpy make series of values for us! This will be very useful once we start manipulating images and making plots.

It is impossible to perform scientific computing in Python without using numpy.

Checking type, length, and shape

It's useful to be able to see some properties of variables we assign. Let's look back at the sequence strings we made earlier and extract some of their properties.

Note that even though the elements of our list_type and tuple_type have mixed types, this command tells us what the type of the object is (i.e. list and tuple). We can force changes in the type of a variable with ease. To demonstrate, let's break up our stitched sequence into the individual basepairs.

We can also convert numbers to strings. This is useful if we want to print a sentence including the output from some other operation. Let's check the length of our two DNA sequences and print it in a sentence. This can be very practical when some part of a string is variable.

We've created a lot of variable so far in this tutorial. It's nice to be able to look at what variables exist in our environment as well as get some information. Let's take a look at everything we've made so far.

We see that we get a relatively nicely ordered list of all of our variables, the type of the variable, and then information about their contents. We can see for our lists and arrays it tells us the number of rows and columns, how many elements there are, what the type of those elements are and so forth.


Functions are arguably the most important components of efficient and effective programming. Functions are sections of code that are written to take an argument, perform some manipulation, and return the manipulated argument. In Python, these functions can be written in the same script where you want to use them.

In Python, spacing and indentation matters. When we define a function and perform looping, we have to be very aware of where our code exists in the script. Once you define a function, all operations that are to take place in that function should be indented from the rest of the code.

The best way to learn is by doing. Let's write a function to add two DNA sequences together and determine its GC content, the percentage of the DNA that is either guanine or cytosine.

We did a lot of complicated procedures in this code, so let's go through it piece by piece.

  1. We defined the function as compute_gc which takes the arguments seq_a and seq_b as well as a keyword argument print_sequence which has a default value of True.
  2. We wrote some information about the what the function does and what arguments it takes. The tripple quoation marks (""") allows us to write strings that go over multiple lines in the code cell.
  3. We then performed the operation by adding together seq_a and seq_b and assigning it to a new variable called merged_sequence.
  4. We tested if the function should print the resut to the screen. We did this by using an if statement. This tested if print_seq was equal to True. If it that was the case, the print function was called and printed the value of merged_sequence.
  5. The GC content is computed and the function is told to return the value.

Each line in this function was one-tab away from the definition statement of the function. Note that we were never specific about what the value of seq_a and what seq_b are.

We should be pleased to see that AT_only has a GC content of 0, GC_only has a GC content of 1.0, and AC_only has a value of 0.5, as we predicted. Since we added the automatic printing of values as a keyword argument, we can easily tell our function to stop printing things.

Being able to write functions to automate tasks will be very valuable in the future $-$ especially when we start working with images.

For Loops

Rather than using "boring" simple operations to learn some syntax, let's learn about the for loop by using a biological example.

Let's say that we have a cell sitting in a tube of growth medium. If we place this tube at the right temperature, the cells will grow exponentially. We can write down a very simple model that as long as the cells are well below the carrying capacity of their environment, they will grow as $$ N(d) = 2^{d}, $$

where $N(d)$ is the number of cells at division $d$. To test this model, we'll write a very short simulation to test that the a cell would grow exponentially.

Before we think of how the specific code should be written, let's write out what our thought process should be.

  1. We should first define the initial number of cells as well as the number of divisions to simulate.
  2. For each cell division, we should multiply the number of cells that we had in the last division event.
  3. After each division, we should keep track of how many cells there are.

With this idea in place, let's go through the code.

We covered a lot of syntax in that cell, so let's take a look at it piece by piece.

Now we enter the for loop, which exectues our simulation.

Also notice that, just like in functions, the code is indented. Everything that is indented to the same level will execute within the loop.

Let's take a look at our N_d list and see how the number of cells changed over time.

It looks like our function worked! But can we tell this is exponential growth? Because this is a simple case, we can see that the number of cells are doubling at each division. However, It would be very useful to plot these results.

Plotting using matplotlib

There are many plotting utilities available for Python. Some notable examples include Bokeh for interactive plotting, Seaborn and Altair for statistical visualization, and a Python port of the popular R programming language plotting utility ggplot. While interactive plotting is likely the visualization tool of the future, the most common (and full featured) plotting utility for Python as of this writing is matplotlib. It was designed with the plotting syntax and style of MATLAB in mind and many of the commands are similiar. As is the case with numpy, matplotlib is not within the standard libray of Python and must be imported.

We would like to see if our simulated cells appear to grow exponentially with time. To do so, we would like to plot the number of cells we have at division number $d$ as a function of $d$. Before we do any plotting, let's generate a vector of division times that matches the size of our N_d vector. We can do this using some of the arrangement methods that we used earlier with numpy. Since we had a measure at $d=0$, our new division vector must have a length of number_of_divisions + 1.

Now all that is left is to plot it! We can use the plot function of matplotlib to generate our scatterplot. We'll choose small circles as our markers and provide the approriate $x$ and $y$ labels as we always should. We'll also add a legend to our plot to show that these data poitns are from a simulation.

In calling the plt.plot() function, we first passed it the $x$ and $y$ data, told it to plot the points as circles (through the 'o' argument), and finally gave it a label.

To me, this plot is pretty ugly. Every aspect of this plot can be stylized to your liking, althought it will take a little bit of work. However, we can import the seaborn plotting utility which will stylize all of our plots and make them much clearer to interpret.

With this imported, let's go ahead and remake the plot from above. We'll also save it using the plt.savefig function.

That's much better!

Asking for help

While we have covered a lot of Python syntax, I don't expect you will have all of it memorized! Every module (nearly) that you will use has a well constructed documentation that explains how functions should be used. Some great examples of this are the documentation pages for NumPy and SciPy, seaborn, and scikit-image.

When you are typing away in the notebook or in an IPython terminal, you can pull up the documentation information for any function or attribute by typing the name followed by a question mark (?). For example (assuming you have numpy imported as np, you can get the documentation for the np.random module by typing the following.

In conclusion...

In this tutorial, we worked through some of the basic syntax of the Python language, learned some crucial programming skills, and even generated a plot of cell growth over time. Through the rest of this course, you will build upon these skills and learn even more interesting and useful tidbits of programming.