Example
In this lesson, we will illustrate the capabilities of Python by running and editing pre-existing code.
This program:
Opens a
.csvfile containing UV-Vis absorption dataConverts its wavelength units to energy units
Finds all peaks in the data above a threshold
Plots the spectrum and peaks to a scientific standard
Saves the figure as a
.pdf
Preparing your folder¶
The easiest way to allow Python programs to interact with files is to store the
source code in the same folder as the file. In this case, we need our .py file
and .csv files in the same place.
Syntax¶
What now follows is a program which reads all the lines of this file which start with a number (allowing us to skip the header). The data is stored by the program and the last x and y data points are printed out as a health check.
"""
UV spectrum analyser
Input a spectrum in nm units and csv format.
"""
import matplotlib.pyplot as plt
# parse csv data
file_name = "benzene_uv-vis_nm.csv"
wavelengths = []
absorbances = []
with open(file_name) as spec_file:
for line in spec_file:
# only conserve lines that start with a number
# to skip header
if line[0].isdigit():
split_line = line.split(",")
wavelengths.append(float(split_line[0]))
absorbances.append(float(split_line[1]))
print(wavelengths[-1],absorbances[-1])Let’s look at a few features of how Python is written, using this as an example.
Top to bottom: Python code is made up of commands for the computer to follow. By default, they are ordered from top to bottom (the first line is executed first, and so on). There are ways to override this rule for our benefit, for example repeating a same line of code hundreds of times without needing to write it repeatedly.
Indentation: The space between the left of the screen and the beginning of Python code is called an indent. In Python, the indentation has a precise meaning for the operation of the code, so it can’t be changed freely to make the program look neater. Generally, indentation is used to modify the top-to-bottom operation of Python.
Colour: Code editors highlight words using different colours to indicate their role in the Python language. It’s as if in English, one colour was reserved for verbs and another for nouns. Some words are invented by the programmer, (like
file_name_), but others are chosen from pre-existing words with meaning (likeimportoropen). Syntax highlighting allows you to notice when you are choosing a word which is already reserved in Python.Comments: Programs can be hard to understand, even by experts. Therefore programmers leave explanatory text to help the reader understand what is going on. These are called comments. Comments can be written by preceding them with a hash symbol (
#) or by encasing multiple lines by two sets of triple quotes (""").Case: Python is case sensitive, which means that capital and lower case letters are not interchangeable. Therefore, while the
print()function is reserved and defined in Python,Print()is not.
Debugging code¶
Let’s complete our code.
You should see a plot on the top right of the window. The spectrum looks fine but our peak detection seems to have failed. Our strategy was to look at each absorbance value and check that it is strictly higher than the value before and after.
Solution
Our solution below will compare candidate peaks with next nearest neighbours instead.
Let’s fix our code with a better peak detection strategy.
Now that our code works as intended, let’s take control of it.
Solution
The line to change reads:
threshold = 3.0Raise the value to something like:
threshold = 3.7Extra functionality¶
We’ve demonstrated how to use Python in basic data processing. You can already take this code and modify it to suit the uses of your own data.
Let’s demonstrate some last tricks that are possible in Python.
Finally, let’s use a more complicated piece of code.
Summary¶
Python can interact with files, analyse data, and plot it.
It is executed top-to-bottom.
Indentation is meaningful and can break the rule above.
Syntax highlighting can help you read code.
Comments are written with
#or""".Python is case-sensitive.
The next lessons will return to basics and teach you the fundamentals of Python. By the end, you should be able to understand everything shown in this lesson’s example.
- Romand, J., & Vodar, B. (1951). Spectres d’absorption du benzène à l’état vapeur et à l’état condensé dans l’ultraviolet lointain. Comptes Rendus, 233, 930–932.