Python for Biologists: Beginner's Guide
Python for Biologists: Beginner's Guide
for Biologists
A programming book for absolute beginners
vi
Contents
Dictionary .............................................................................. 53
7.1. dict() constructor ................................................................................................. 54
7.2. Dictionary keys ............................................................................................................. 54
7.3. Using in keyword and get() method on a dictionary ....................................... 54
7.4. Extract all keys & values, or both .............................................................................. 55
7.5. Getting the length of a dictionary .............................................................................. 56
7.6. Update and merge dictionaries ................................................................................... 57
7.7. Dictionary comprehension .......................................................................................... 58
Set .......................................................................................... 59
8.1. set() constructor .................................................................................................... 59
8.2. Functions and operators on set .................................................................................. 59
Conditional Statements ......................................................... 61
9.1. Conditions ..................................................................................................................... 62
9.2. if Statement ............................................................................................................... 62
9.3. Loops.............................................................................................................................. 66
9.3.1. while Loop .............................................................................................. 66
9.3.2. for Loop.................................................................................................... 68
9.3.3. continue and break .......................................................................... 68
9.4. enumerate() function ......................................................................................... 70
9.5. range() function .................................................................................................... 72
9.6. Improving amino_acid_decoder ................................................................................ 73
File Handling ........................................................................ 75
10.1. Opening a file .............................................................................................................. 75
10.2. Reading a file ............................................................................................................... 76
10.2.1. read(), readline(), and readlines() method ................ 77
10.2.2. Using for loop ......................................................................................... 79
10.3. Writing a file ................................................................................................................ 80
10.4. close().................................................................................................................... 80
Functions ............................................................................... 82
11.1. Defining a function .................................................................................................... 82
11.2. Positional and keyword arguments .......................................................................... 84
11.3. Default argument values ............................................................................................ 87
vii
Contents
viii
Hello World!
Welcome to the Basic Python Programming for Biologists; a book written to introduce
beginners to the world of programming!
Hey pal, you know what, learning programming is like learning Spanish, or French!
Programming languages like Python, are like natural languages. We use natural
languages to communicate with others while with programming languages we can
communicate with a computer. Like any other language, it also has grammar called
syntax. The only difference is that there is no talking involved. It only works in
writing!
Here, I am assuming that you are an absolute beginner in programming, with a lot
of curiosity and enthusiasm to learn it! You may or may not have formal training in
biology. That does not matter. What matters is a little perseverance because
computer programming is abstract and sometimes it needs a little extra effort to
work out! Chapters of this book are like pieces of a jigsaw puzzle. When you join
these progressively, you will get the bigger picture and you will become increasingly
comfortable with the language. So, stick to it and keep the faith. The book will
upgrade your programming knowledge from the ‘Absolute Beginner’ to ‘Ready for
Intermediate’! Also remember, learning to program is a continuous process and, as
with other lessons, profoundly depends on practice. I suggest investing at least an
hour daily to get a good grip on the subject.
0.1. Python
Python is an interpreted, object-oriented, high-level programming language. It has a simple,
easy to learn syntax that emphasizes readability and therefore, perfect for absolute
beginners. The Dutch programmer Guido van Rossum created Python at Stichting
Mathematisch Centrum (CWI) in the Netherlands as a successor of a language called
ABC. He published the first version of the Python code in early 1991. Guido van
Rossum remains Python’s principal author, although it includes many contributions
from others with time. Guido van Rossum, himself has written, “I chose Python as a
working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python’s
Flying Circus)”. That indicates, the name is not related to Python, the snake. It came
from the famous BBC comedy series Monty Python’s Flying Circus.
2
Chapter 0: Hello World!
I also request you to consult the Glossary whenever you face jargon. This book has
an extensive glossary, primarily adopted, and remixed from Prof. Allen B. Downey’s
Think Python; an exceptionally excellent book for beginners. You may find the
sequence of topics different from other beginner programming books because I have
arranged the chapters in accordance with the needs of biologists, who are taking
baby steps in the world of programming. Do not worry, just go with the flow!
0.3. Acknowledgement
Many thanks to Prof. Allen Downey, Dr. Charles R. Severance and Dr. Martin Jones
for making their exceptional books, Think Python, Python for Everybody and Python for
Biologists, respectively, available under the terms of the Creative Commons
Attribution-NonCommercial 3.0 Unported License.
3
Chapter 0: Hello World!
Thanks to Dr. Debnarayan Roy, Principal, Jhargram Raj College for his continued
patronage and encouragement.
Special thanks to the editor and my wife, Dr. Nabanita Ghosh, Assistant Professor in
Zoology, Maulana Azad College. Without her professional support, the book would
not see the light of day. Her exceptionally strong optimism motivates me in the lows
of my life.
Finally, lots of love for my parents, Mr. Bijonmay Sinha & Mrs. Sandhya Sinha. Their
unconditional love and enthusiasm keep me enthused in all highs and lows of life. As
always, their gusto about the project keeps me motivated in these tough times.
0.4. Feedback
I humbly request you to give your suggestions, comments, and feedback on the book
to krishnendupython@[Link]. This will help a lot to refine the book in the
coming days. It will be my pleasure to duly acknowledge your valuable contribution
in further editions.
Happy programming,
Krishnendu Sinha
Email: krishnendupython@[Link]
Website: [Link]
4
Getting Started
Theoretically, you can write your code anywhere, even on the back of an envelope and
to do so, you must be familiar with Python Syntax. This book is all about that. It will
make you familiar with Python syntax and its data structure. However, to run your code,
have Python and its Interpreter installed into your PC.
Here one thing is worth mentioning. First, you will find a very cool feature of Python’s
IDLE when you write your code there. It differentially colours different functional
parts of the code. Besides the aesthetics, it helps you to avoid unnecessary confusion
and write less erroneous code. You will understand the importance of differential
colour coding in due course.
However, Shell has a downside. Every time Shell starts afresh. Though is a convenient
tool for testing and learning Python commands, you cannot use the Shell to
compose an actual program. For practical programming, IDLE has its text editor. Figure
1-3 illustrates steps to access it.
Run the Python script following the process shown in Figure 1-5. A script gives its
output in the shell upon running. If you get the desired output (i.e., Hello World!)
in shell, congratulations! You have made it to your first program!
6
Chapter 1: Getting Started
Click to download
7
Chapter 1: Getting Started
8
Chapter 1: Getting Started
Figure 1-3. Accessing IDLE text editor. From File menu in IDLE Shell clicking the New File opens a
new (untitled) text editor in a separate window.
9
Chapter 1: Getting Started
Code statement
10
Chapter 1: Getting Started
11
Types, Variable & Operators
In the previous chapter, I have introduced you to the Python interpreter. You have
written your first line of code. You have also created a Python script. Now it is time
to understand the building blocks, components, and structure of Python code. But
first, a brief discussion of data will be beneficial.
2.1. Data
In simple term, computer data is the information (e.g., text, images, audio, etc) stored
and (or) processed by a computer. Data can be anything like the quantities,
characters, or symbols on which a computer performs operations. At the
rudimentary level, data is just a sequence of bits. One insight of computing is that we
can interpret those bits any way we want—as data of various values and types
(numbers, text characters) or even as computer code itself. We use Python to define
chunks of these bits for different purposes and to get them to and from the CPU.
2.2. Statement
The first code you encountered was >>> print(“Hello World!”).
In literature, we denote this kind of line as a sentence, but in programming,
programmers denote this as the statement. Henceforth, I shall use this term for any
executable line of code.
13
Chapter 2: Types, Variable & Operators
2.4. Comments
Now look again closely in CodeEx 2-1. You might notice I started the first line with
the hash (#) sign. Python interpreter ignores everything that starts with # while
executing a code. In Python, this type of line starting with # is called comment CodeEx
2-2
. Comment is NOT a part of an executable code. Programmers use comments to
annotate a code to make it more readable to other programmers. Comments are
there for human, not for a computer! Without proper comments, even an excellent
program becomes useless over time or at least very hard to read in future
modifications! Always annotate your code for your own good!
14
Chapter 2: Types, Variable & Operators
Object
Everything in Python (e.g., data types, functions, programs etc) are objects. An object
is an instance of a class. A class can create many objects. Confused? Let me explain
the idea with an example.
Say you have a cookie template shaped like a star. Now if you consider this template
as a class, the star-cookies made with it are instances of the class and thus are objects
that belong to the star-template class. Now if you have a Christmas tree-shaped
cookie, it belongs to a different class, Christmas tree-template. Now, the ingredients
of the cookies are the values of the object. Until it is baked you can play with the
ingredients, can make desirable changes like adding Choco or almond chips. At this
point, the cookie is called a mutable object. Once baked you can’t make further
alterations to its ingredients, aka value. Then, the cookie will be called an immutable
object. Though in reality, mutability is not the two stages of the same object. Few
objects are born mutable, while others are born immutable. Few types create mutable
objects while others create immutable objects. Table 2-1 explicitly showcases
important basic data types (aka classes) of Python.
Now, from the storage perspective, if you store the cookies in jars, you can use an
external label to name those jars, say as choco or almond cookies. This labelling or
tagging will make it easier to find a jar with specific cookies in future. This ‘tag’ is the
variable assigned to the object (cookie) with a specific value (Choco-chip/almond).
You will find more about variables in the next section.
type() function
In case of any confusion about the type of object, type() function helps. type()
takes an object as an argument and returns its class or typeCodeEx 2-3.
15
Chapter 2: Types, Variable & Operators
16
Chapter 2: Types, Variable & Operators
Type casting
Python allows us to convert one data type to another (e.g., int to str or str to
int etc). Casting one type to another is called type casting and Python has three built-
in functions to perform the task: str(), int() and float() functions.
17
Chapter 2: Types, Variable & Operators
CodeEx 2-5
2.6. Variables
Variable is a name that refers to a data value.
Revisit the cookie’s example. The labels on the cookie jars were analogous to
variables. Similarly, we assign a variable to a value to store the value in physical
memory so that we can easily access and reuse it in future. In programming, we use
the phrase ‘initializing a variable’ instead of ‘creating a variable’ ( e.g., ‘initializing a
variable x and assigning it to the value y’). After initializing a variable, the computer
allocates a certain amount of memory space to it to store its associated value. You
can access the value by referring to the assigned variable’s name. Now from here,
you must remember one thing: ‘variables are only names!’
18
Chapter 2: Types, Variable & Operators
Python has no command for declaring a variable. Python initializes a variable at the
moment you assign a value to it. We call the process of assigning a value to a variable
as assignment. Python’s assignment statement does this job with the help of the assignment
19
Chapter 2: Types, Variable & Operators
An example can make you understand easily the necessity of a variable. Suppose you
have a DNA sequence, AATTCGATTCAGCTACTCAT, to work with. As of now,
you know how to print a string in the console. So, let the DNA string be printedCodeEx
2-9
.
Now if you consider, you can find a problem here. The above code is a single line
simple code and it uses the DNA string only once. But in the actual world, within a
program, you might use this string many times for performing different tasks. You
can imagine that writing this 20-nt long DNA string multiple times from scratch is a
headache! And not to forget, under real circumstances we should work with the
enormous size of DNA strings! Python can easily address this problem by assigning a
20
Chapter 2: Types, Variable & Operators
variable (e.g., dna_1) to this stringCodeEx 2-10. I named the variable as dna_1, but it
can be anything else, provided the name follows Python’s variables nomenclature
rules as follows.
Table 2-2 listed a few examples of valid and invalid names. Hope this will help you pick
syntactically correct variable names. However, by convention, two ways of naming a
21
Chapter 2: Types, Variable & Operators
variable are mostly popular among Python programmers. They either use the camel
case notation or use underscoresCodeEx 2-11. Also, note here, value-less variable elicits an
errorCodeEx 2-11.
Table 2-2. Instances of few valid and invalid variable names in Python
Valid names Invalid names
dna 1dna
DNA 1
d_n_a_10 10_dna
_rna dna!
_1rna dna-1
22
Chapter 2: Types, Variable & Operators
23
Chapter 2: Types, Variable & Operators
not bad. These help us improve our codes and ultimately make them error-free.
There are two distinguishable kinds of errors: syntax errors and exceptions.
24
Chapter 2: Types, Variable & Operators
Syntax errors
This type of error arises when Python’s syntax gets violatedCodeEx 2-13. This is the most
common type of error a learner encounters.
Exceptions
Even a syntactically correct statement or expression can cause an error when one
attempts to execute it. These types of error are cumulatively referred to as exceptions
and are detected during executionCodeEx 2-14.
25
String Manipulation
Till now you have been exposed to jargons and key concepts which were an absolute
prerequisite for understanding syntax and starting programming in Python. String
denotes text in Python and among all data types, it is of the utmost importance in
biology. Researchers store the enormous amount of data produced through modern
sequencing techniques in simple text format. Python treats these data as string
sequences! Biologists need programming to extract a significant amount of
information from these data, and for that training in string manipulation is necessary.
27
Chapter 3: String Manipulation
Suppose, you would like to use a single quote within a string which is also single-
quotedline-3: CodeEx 3-3. But according to Python’s syntax, it’s illegalline 4: CodeEx 3-3. You can’t
use the same quotes within a string that is used to designate it. But the escape
character allows you to do soline-6 to 8: CodeEx 3-3. Another highly used special character is
the newline character (\n). Using this character, you can create an indentation within
a string that is otherwise not permissible without triple quotesline 12 to 16: CodeEx 3-3.
str A T T G C A A C G T
Index 0 1 2 3 4 5 6 7 8 9
28
Chapter 3: String Manipulation
30
Chapter 3: String Manipulation
change the case of a string by built-in methods, upper() and lower(). As the
name suggests, upper() converts lowercase strings to uppercase and vice
versaCodeEx 3-8.
31
Chapter 3: String Manipulation
32
Chapter 3: String Manipulation
Here note that with multiple occurrences it only returns the index of the first
occurrence. String ‘attgactgacg’ has two ‘tga’ motifs at index 2 and 6.
33
Chapter 3: String Manipulation
You need multiple tools along with find() for extracting indexes of all the
occurrences. I will introduce you to these additional tools in the following chapters.
34
Interactive Program
Now you can solve many problems with the bit of skill you have already developed.
But one thing is missing! I did not describe interactive programming. People imagine
programs as an interactive sort of machine. Take the example of a calculator. A
calculator is a program. You put some values in it and specify the arithmetic
operations to perform on that. Accordingly, you will get the result. Even, it will let
you know if you have made some error, like dividing a number with 0! In short, the
calculator takes user input, perform the user-specified task, and gives the output.
That’s what people are familiar with, and that’s the beauty of programming!
1 >>> #asking user for DNA string as an input and storing the
2 >>> #input in a variable, user_dna
3 >>>
4 >>> user_dna = input(‘provide DNA seq:’)
5 provide DNA seq: ATGCGCAT
6 >>>
CodeEx 4-1
Chapter 4: Interactive Program
However, it’s not useful to write an interactive code in the shell. As discussed earlier,
for storing a code as a script for subsequent uses, open the text editor from IDLE,
write the code and save it as a python script (.py) with a proper name. Now you
can run the script any time you want to calculate the length of a DNA sequence!
Upon running, it prompts for a DNA sequence in the shell. Upon entering the
sequence data and hitting enter, the program prints the result on the screen. As a
guide, you can consult Figure 4-1.
36
Chapter 4: Interactive Program
pyinstaller
Now, to convert .py to .exe you only need a Python library package, the
pyinstaller. First, install pyinstaller in your Python directory. To do so,
open the Windows command prompt by searching cmd in Windows search. Then type
pip install pyinstaller and hit enterFigure 4-2. It will install within a
minute. After the pyinstaller installation is complete, follow these steps to
make your script executable Figure 4-3&Figure 4-4.
1. Navigate to the folder where you stored the Python script, ([Link]).
Then press shift and right click simultaneously.
2. From the pop-up menu click on ‘Open PowerShell window here’.
3. A PowerShell window will open. Now write,
pyinstaller [Link] and hit enter. pyinstaller will create
the executable file. To access it open the newly created dist folder (created in
the same location where you stored the .py file).
37
Chapter 4: Interactive Program
4. Within the folder, there is another folder, dnalencal. Open it and within the
dnalencal folder press the shift key and right-click to open Windows
PowerShell.
5. In the PowerShell write the name of the file ([Link]) created and
hit the tab button on the keyboard. A prompt will appear upon hitting the tab.
Put your data in the prompt and see the result! Always keep the dist folder
and all its content undisturbed. Extracting a .exe file from dist may create
unexpected errors while running it.
Figure 4-1: Guide to saving the program as a Python script ([Link]) and running it.
38
Chapter 4: Interactive Program
a
b
39
Chapter 4: Interactive Program
40
List
As mentioned in Chapter 2 there are four core built-in container data types in Python.
Container data types are used to store multiple objects. These are list, tuple, dictionary
and set. These are the most basic data structures of Python. I have dedicated this
chapter to the list. I will discuss the other three data structures in the next three
chapters.
Lists are used to store an ordered collection of values that are usually related. It is used
to store multiple values in a single variable. You can declare a list using square brackets
with zero to more than one value in a comma-separated manner.
The values that make up a list are called elements or items of that list. Both are used
interchangeably. List elements could belong to any data type. Even a list could be an
element of another list in a complex data structure. Hence, it is considered as a
heterogeneous data type. You also can declare a list without putting any element in it.
This kind of list is known as an empty list. Refer to CodeEx 5-1 for a clearer picture.
>>> #[list]
>>>
>>> dna_list = [‘ATGC’,‘ATTG’,‘GTAC’]
>>> type(dna_list)
<class ‘list’>
>>>
>>> #here single variable dna_list storing multiple values of
>>> # DNA seq in a comma separated manner
>>>
>>> #declaring empty list (i.e., list w/o elements)
>>>
>>> empty_list = []
>>> type(empty_list)
<class ‘list’>
>>>
CodeEx 5-1
42
Chapter 5: List
the item to be inserted as its argument. insert() takes two arguments. The first
positional argument is the desirable index of the new element to be inserted. While
the second positional argument is the new element itself. Just note that, both the
method updates the existing list without creating a new one with updated items.
43
Chapter 5: List
CodeEx 5-6
44
Chapter 5: List
45
Chapter 5: List
46
Chapter 5: List
empty string, or white space or comma or anything of your choice. Hence join()
method could join list elements into a stringCodeEx 5-11.
47
Chapter 5: List
sub-section after completing the for loop section of the Conditional Statement
chapter.
zip() takes iterable objects as argument and return a zip object as output. Hope
CodeEx 5-13 will clarify your understanding of the function. Now, let’s create an
Amino Acid Dictionary that will have single letter code as key and triplet code as
value. Please revisit this section after completing the Dictionary chapter for a clearer
understanding. How zip() holds data, while it completes iteration, is an interesting
matter to discuss. The value returned by zip() is an iterator of tuples that you can
turn into a list, tuple, etc. If we parallelly iterate over n-numbers of iterables, zip()
will hold the corresponding value to an iterator of tuples with n-number of an item
in each, where the first item in each passed iterator is paired together, likewise, the
second item in each passed iterator is paired together and so on. If the passed
iterators have different lengths, the iterator with the least elements decides the
length of the new iterator. zip() stops when the shortest sequence is overCodeEx
5-14
.
48
Chapter 5: List
Here in CodeEx 5-16, the list comprehension statement takes each element of the
list codon_lst and slices them using the slicer to form paired value items of the
newly paired value list codon_lst_pv. For each item in codon_lst, the last
49
Chapter 5: List
character indicates an amino acid where the first three characters indicate respective
triplet codon.
>>> #enumerate(iterables,start=0)
>>> list_1 = [‘a’, ‘t’, ‘g’, ‘a’]
>>> en = enumerate(list_1) #en is the enumerate object
>>> type(en)
<class ‘enumerate’>
>>> list(en)
[(0, ‘a’), (1, ‘t’), (2, ‘g’), (3, ‘a’)]
>>> for i,j in enumerate(list_1):
print('index:',i,'item:',j)
index: 0 item: a
index: 1 item: t
index: 2 item: g
index: 3 item: a
>>>
CodeEx 5-17
50
Tuple
The tuple is an ordered, heterogeneous, immutable data type that allows duplicates as its
item value. You can imagine a tuple as an immutable list. It is used to store an
ordered collection of data values where the user prefers the immutability of the data.
You can declare tuples using round brackets. Values of a tuple are comma
separatedCodeEx 6-1.
>>> #(tuple)
>>>
>>> #declairing empty tuple
>>>
>>> t = ()
>>> type(t)
<class ‘tuple’>
>>>
>>> #multiple-item tuple
>>>
>>> triplet = (‘AAA’,‘TTT’,‘GGG’,‘CCC’)
>>> type(triplet)
<class ‘tuple’>
>>>
CodeEx 6-1
52
Dictionary
Suppose you need to use restriction site sequences for more than one restriction
endonuclease (REs) throughout your program. Or, you need to store and reuse the
amino acids and their single-letter codes for your project. What will you do?
In one option, you can create a list of restriction site sequences and remember their
order to relate them with their respective RE. Even better, create two lists. One for
restriction site sequences and another for REs. Now maintain strict order so that you
can tally those indexes and with help of an iteration tool (e.g., zip() or for loop,
etc.), you can extract restriction site sequences without error.
But isn’t it too cumbersome and error-prone? As list are mutable, any error on your
part can break your program or can give you false output! Like you need the
sequence for EcoRI but getting that of BamH1 because of a silly indexing error on
your part! That’s not acceptable at all!
Fortunately, Python has an incredible built-in container just for these purposes,
where tagging a value and retrieving it using the tag is easy! It’s called the Dictionary!
Dictionaries are collections of values that are mapped to arbitrary, immutable, and
unique keys. These store data values in a key-value pair where each value has a unique
key. These key-value pairs are the items of a dictionary.
Dictionary is mutable, while keys are immutable (e.g., str, int, etc.). It is an ordered
data structure (Since Python 3.7). It does not allow duplicate keys.
>>> #{dictionary}
>>>
>>> re_dict = {‘ecor1’:‘GAATTC’,
‘bamh1’:‘GGATCC’,
‘hind3’:‘aagcct’}
>>> type(re_dict)
<class ‘dict’>
>>> #empty dictionary (i.e., dict w/o elements)
>>> empty = {}
>>> type(empty)
<class ‘dict’>
>>>
CodeEx 7-1
CodeEx 7-2
54
Chapter 7: Dictionary
whereas False indicates its absence. Also, you can access the value mapped with
the key with get() methodCodeEx 7-4.
55
Chapter 7: Dictionary
‘dict_keys’>) contains the keys as a list. So, it’s best to always pass outputs
from these methods through list(), if you want to print these outputs directly
(list[[Link]()]). See CodeEx 7-5 for more details
56
Chapter 7: Dictionary
57
Chapter 7: Dictionary
CodeEx 7-9
58
Set
Set is an unordered, heterogeneous data types that do not allow duplicates in its items.
Though the set is mutable, its items must be immutable. One can imagine set as a
dictionary made up of only key values. You can declare sets using curly brackets as a
dictionary with multiple comma-separated valuesCodeEx 8-1.
>>> #{set}
>>>
>>> s = {‘A’,‘B’,1,5}
>>> type(s)
<class ‘set’>
>>> print(s)
{'a', 1, 5, 'b'}
>>>
>>> #print(s) outcome could be different each time you call it
>>> #a fresh. This is because set is inherently unordered.
CodeEx 8-1
1
>>> #set from string
>>>
2 >>> aa = ‘QTSA’
>>> aa_set = set(aa)
>>> print(aa_set)
{‘Q’, ‘T’, ‘S’, ‘A’}
>>>
>>> #list to set
>>>
>>> list2set = set([‘Q’, ‘T’, ‘S’, ‘A’])
>>> print(list2set)
{‘Q’, ‘T’, ‘S’, ‘A’}
>>>
>>> #etc.
>>>
CodeEx 8-2
60
Conditional Statements
You just have landed in a very interesting section of this book! Till now, you have
been exposed to simple programs only. In the actual world, you will face complex
problems and for that, you need to come up with complex programs with multiple
checkpoints and decision-making nodes. These nodes and checkpoints control the
flow of a program and believe me, that is important. After completing this chapter,
you will be able to create smarter programs that can make their own decisions.
For example, imagine a situation where there is a demand for DNA fragments whose
GC-content is greater than 50%. You can create a custom GC-Content Calculator to
meet the demand. It takes input from a user and returns GC-content in percentage.
Pretty simple? No. In practice, mistakes happen! A user may mistakenly put integer
instead of a nucleotide string! This situation will inevitably trigger the hidden bug of
the program! You can only overcome such situations if you can control the flow of
our program.
Now, what is meant by the phrase ‘flow control’ or ‘control flow’? You already have
noticed that by default, Python’s interpreter sequentially executes a program’s code in a
top-down fashion. But most of the time, this simple strategy does not work. In day-to-
day life, we modulate our mode of action according to the conditions we face.
Likewise, to write a useful program, we almost always need the ability to check
conditions and change the behaviour of the program accordingly. Conditions create
logical branches within a programFigure 9-1. Based on different conditions a program may
execute one such branch or may pass it to execute a different branch. It may also
repeatedly execute a block of code until a condition holds, a phenomenon known as
Chapter 9: Conditional Statements
looping. A conditional statement gives us these abilities. It controls the default flow of a
program.
9.1. Conditions
A Boolean expression, which returns either True or False is a condition.
Comparison operators, identity operator along a few other operators and methods are
widely used to compose a condition. You can also couple simple conditions with
logical operators to form complex conditions. Refer to CodeEx 9-1 for related
examples.
9.2. if Statement
The simplest conditional statement is the if statement. Structurally the if
statement has a header (line-4; CodeEx 9-2) followed by an indented (line-5 to 7;
CodeEx 9-2) body of code called a block of code or suite. We call statements like this
compound statements (line-4 to 7; CodeEx 9-2). if evaluate whether the statement met
a certain condition. If the condition stands True then and only then if executes its
suite. See CodeEx 9-2 for better understanding.
For more complex situations we need more than one branch. Along with if, elif
and else is used to create multiple chained conditions that lead to multiple branches.
elif is a pythonic way to say “else if”. There can be zero or more elif parts and zero
62
Chapter 9: Conditional Statements
CodeEx 9-1
63
Chapter 9: Conditional Statements
1 1 #structure of if statement
2
3 2 x = input('x = ')
4 if int(x)>0:
5 y = int(x)+1
6 print('x is positive')
7 print('y is greater than 1')
1 # if-elif-else
2
3 x = input('x = ')
4 if int(x)>0:
5 print('x is positive')
6 elif int(x)<0:
7 print('x is negative')
8 else:
9 print(‘x is Zero’)
64
Chapter 9: Conditional Statements
or only one else part. Remember Python sequentially executes chained conditions and
skip a suite if only its condition stands False. CodeEx 9-3 will execute line-5 if
line-4 stands True, will execute line-7 if only line-6 stands True and will execute
line-9 only if line-4 and 6 both stand False. Execution stops upon finding the first
True condition.
Figure 9-1: Algorithmic flow chart of amino_acid_decoder showing its complex branching
pattern where each node represents a condition embedded in if/elif/if-else statements.
65
Chapter 9: Conditional Statements
1 #amino_acid_decoder
2
3 user_input = input(‘Enter single-letter amino acid code:’)
4 input_aa = user_input.upper()
5 if input_aa == ‘R’:
6 print(input_aa, ‘stands for Arginine(Arg)’)
7 elif input_aa == ‘N’:
8 print(input_aa, ‘stands for Asparagine(Asn)’)
9 elif input_aa == 'D':
10 print(input_aa, ‘stands for Aspartic Acid(Asp)’)
11 else:
12 print(‘Error: Decoder only accept SINGLE-LETTER AA Code’)
13
14 ‘‘‘NB: After line 10, please insert similar elif statements for
15 rest 17 amino acids. While doing so,watch your indentations!’’’
9.3. Loops
Often in programming, we need another kind of flow control mechanism which let
us repeatedly execute a block of code. This kind of conditional execution is possible
with a category of conditional statements, called loops. Python has while loop and
for loop in this category. while loop is preferable when a programmer does not
know the exact number of iterations required. That means in prior, we don’t know
how many times that loop has to be repeated. In contrast, for loop is appropriate
when in prior we know exactly the number of iterations needed.
while Loop
while loop iterate over a sequence of statements until a certain condition stands
True. That is why it is also known as an indefinite loop. Structurally the while loop
has a header, ended with a colon (:), followed by an indented block of code.
66
Chapter 9: Conditional Statements
A loop counter is often used with a while loop. It’s just a variable initialized with a
value according to the program’s need (x of line-3 in CodeEx 9-5). It is declared
outside the loop statement and used to create a condition for the loop. However, the
body of the loop must update the value of the loop counter (line 6; CodeEx 9-5) so
that the condition becomes False eventually, and the loop terminates. CodeEx 9-5
updates the value of x in each loop cycle by (-1) so that the condition (i.e., x>=0)
becomes False (i.e., x<0) eventually and the loop ends. Though a while loop
looks simple, be cautious while creating it! If you don’t be careful, you could enter an
infinite loopCodeEx 9-6, a loop that will repeat forever! Just omitting the counter-updating
statement, line-6 of CodeEx 9-5, will give you the ticket to an infinite loop!
CodeEx 9-6
67
Chapter 9: Conditional Statements
for Loop
In contrast to the while loop, for loop, iterate over an iterable object. It runs
through as many iterations as there are items in that object. Thus, it is also called a
definite loop. Structurally, for statement is like a while statement. It has a
header (line-4; CodeEx 9-7), ending with a colon (:), followed by an indented block of
code (line-5; CodeEx 9-7). Except it has an in keyword within the header, before the
iterable object. See CodeEx 9-7.
CodeEx 9-8 demonstrates how for loop is used to iterate over string and list object.
Follow it carefully. By iterating over an iterable object, for loop could extract its
constituent items or characters.
68
Chapter 9: Conditional Statements
AA: Q
AA: H
AA: I
AA: L
AA: K
>>>
>>> #using for loop to iterate over a list
>>> #taking a list of gene
>>>
>>> gene = [‘GAPDH’,‘p53’,‘actin’,‘SOD2’]
>>>
>>> #using for statement to extract element genes from gene
>>>
>>> for g in gene:
print(‘Gene: ’,g)
Gene: GAPDH
Gene: p53
Gene: actin
Gene: SOD2
>>>
CodeEx 9-8
break statement which is line-5. Here if x becomes 2, the loop prematurely ends.
Also, when x becomes 4 (line-7 and 8) loop aborts that iteration after line 8 and
jumps to the next iteration. CodeEx 9-10 follows the same mechanism. Follow line-4
to 8 and compare the for loop’s output.
69
Chapter 9: Conditional Statements
70
Chapter 9: Conditional Statements
1 >>> # enumerate()function
>>>
2 >>> peptide = ‘QHILK’
>>> enu_obj = enumerate(peptide)#enu_obj is an enumerate
object
>>> list(enu_obj) #casting enumerate object to list
[(0, 'Q'), (1, 'H'), (2, 'I'), (3, 'L'), (4, 'K')]
>>>
>>> print(enu_obj) # enu_obj can’t be printed directly
<enumerate object at 0x0000020D71ACACC0>
>>>
>>> type(enu_obj) #checking class of enu_obj
<class 'enumerate'>
>>>
CodeEx 9-11
71
Chapter 9: Conditional Statements
>>> #range(start,stop,step)function
>>>
>>> r = range(5) #r is the range object
>>> list(r) #casting range object into list to see its content
[0, 1, 2, 3, 4]
>>> print(r) #range object can’t be directly printed
range(0, 5)
>>> type(r) #checking class of range object
<class 'range'>
>>> r1 = range(1,5) #specifying range with start and endpoint
>>> list(r1)
[1, 2, 3, 4]
>>> r2 =range(1,10,2) #specifying with increment step of 2
>>> list(r2)
[1, 3, 5, 7, 9]
>>>
>>> #iterating over range()with for loop
>>> for i in range(1,10,2):
print(i)
1
3
5
7
9
>>>
CodeEx 9-13
72
Chapter 9: Conditional Statements
Now, say you need to create a 12-nt long poly-adenine string. Using a for loop you
can automate the workCodeEx 9-14. But a for loop needs an iterable object to iterate
over in generating the polymer. How could you supply the iterable? Here range()
comes in handy. In CodeEx 9-14, range(12) created an iterable sequence with 12
items, from 0 to 11line-4. Then with every iteration, the variable polya is getting
updated with an adenine baseline-5. This looping goes on until the iterable sequence
gets exhausted, i.e., the loop runs 12 times and reaches the last item of the integer
sequence. By that time 12 adenine bases have been added to the polya, creating a
12-nt poly-A polymer.
73
Chapter 9: Conditional Statements
1 #amino_acid_decoder
2 #dict containing 20 amino acids with triplet code and MW
3 aa_dict = {'A':'Alanine(Ala); MW:89.09',
4 'R':'Arginine(Arg); MW:174.20',
5 'N':'Asparagine(Asn); MW:132.12',
6 'D':'Aspartic Acid(Asp);MW:133.10',
7 'C':'Cysteine(Cys);MW:121.16',
8 'E':'Glutamic Acid(Glu);MW:147.13',
9 'Q':'Glutamine(Gln);MW:146.15',
10 'G':'Glycine(Gly);MW:75.07',
11 'H':'Histidine(His);MW:155.16',
12 'I':'Isoleucine(Ile);MW:131.18',
13 'L':'Leucine(Leu);MW:131.18',
14 'K':'Lysine(Lys);MW:146.19',
15 'M':'Methionine(Met);MW:149.21',
16 'F':'Phenylalanine(Phe);MW:165.19',
17 'P':'Proline(Pro);MW:115.13',
18 'S':'Serine(Ser);MW:105.09',
19 'T':'Threonine(Thr);MW:119.12',
20 'W':'Tryptophan(Trp);MW:204.23',
21 'Y':'Tyrosine(Tyr);MW:181.19',
22 'V':'Valine(Val);MW:117.15'}
23
24 while True:
25 user_input = input(‘Enter single-letter amino acid code:’)
26 input_aa = user_input.upper()
27 if input_aa in aa_dict:
28 print(aa_dict[input_aa])
29 elif input_aa not in aa_dict and input_aa != 'X':
30 print(‘Sorry,’,input_aa,‘ does not code an AA!’)
31 elif input_aa == 'X':
32 print(‘Thanks for using amino_acid_decoder’)
33 break
34 else:
35 print('InputError: Kindly input SINGLE-LETTER AA Code')
36
37 #enter letter X if you want to close the program
74
File Handling
Files are very important in computational biology and there are good reasons for
that. I have used very small DNA sequences in coding examples to keep it
manageable. But as you know, real biological data are enormous. Even a relatively
simple organism like [Link] has a genome size of 4.6 × 106 bp. The only practical way
to handle such data is to store it in a file and directly access it from that file. In such
cases, a program must access the file data. Also, the program preferably stores the
output in another file so that, it can be shared and used in future with ease. In this
chapter, you will take a close look at how to work with files. Among different file
format, simple text and FASTA files are mostly used in biology.
careful with write-mode as opening a file in write-mode overwrites and clears any
existing data. It also creates a file if the file with the specified name does not exist
in the specified directory.
3. Append-mode: represented by ‘a’. Files opened in append-mode are also eligible
for modification. The difference with write-mode is that instead of overwriting, it
allows appending new data at the end of the existing data.
76
Chapter 10: File Handling
However, instead of accessing all the lines, the readline() method returns one
line at a time. Each time the readline() is called, it reads a new line. By calling
readline() twice, you can read the first two lines, by calling it thrice you can
77
Chapter 10: File Handling
read the first three lines and so on. Whereas, the readlines() method returns a
list containing all the lines of the text file as its elements. See CodeEx 10-4.
You might have noticed new lines are inserted after each line (line 7, line 11, and line
15 in CodeEx 10-4). It is due to a new line character (\n) “hidden” at the end of
78
Chapter 10: File Handling
each line, except the last line. When you see a new line in a text file, that indicates a
cryptic \n has been inserted at the end. The readline() and readlines()
functions reveal the hidden \n. Also, behind the scene, print() by default adds
an \n at the end of the supplied argument for printing. These two \n adds up to
give a blank space. It is just like hitting the two enter button on a keyboard when you
are writing something. A \n is just like a physical enter button on a keyboard.
However, there are many ways to avoid this effect like using string method
rstrip()1 with ‘\n’ as argumentCodeEx 10-5 or replacing default ‘\n’ of the keyword
argument end with an empty string when calling print()(line 11 & 12 in CodeEx
10-5), etc.
1It removes the character of the arguments from the end of a string. By default, it removes any tailing
spaces from strings.
79
Chapter 10: File Handling
AAAA
TTTT
GGGG
CCCC
>>> [Link]()
>>>
CodeEx 10-6
10.4. close()
You have already seen the use of the close() method at code examples, >>>
[Link](). In CodeEx 10-5, after reading and printing the first
three lines, line-13, [Link]() explicitly closes the file. To use the file again, it
needs to be reopened. It is a good practice to always close the file once you finish
working with it. This habit will avert unnecessary complications in the future.
Here it’s worth mentioning that with with statement, we can omit the use of the
closing statement. After exiting the with statement, a file opened with it gets closed
implicitly. See CodeEx 10-8 for the syntax of with statement.
80
Chapter 10: File Handling
1
>>> #writing content to a file
>>>
>>> #creating a new file, new_file_1.txt, in Desktop directory
>>> f = open(r‘C:\Users\Desktop\new_file_1.txt’,‘w’)
>>>
>>> #writing sequence ATGC to the newly created file
>>> [Link](‘ATGC’)
4
>>> [Link]()
>>>
>>> #checking the newly created file content
>>> f1 = open(r‘C:\Users\Desktop\new_file_1.txt’)
>>> print([Link]())
ATGC
>>> [Link]()
>>>
>>> #now appending GGTT seq as a new line in new_file_1.txt
>>> f2 = open(r‘C:\Users\Desktop\new_file_1.txt’,‘a’)
>>> [Link](‘\nGGTT’)
5
>>> [Link]()
>>>
>>> #againg checking the updated new_file_1.txt
>>> f3 = open(r‘C:\Users\Desktop\new_file_1.txt’)
>>> print([Link]())
ATGC
GGTT
>>> [Link]()
>>>
CodeEx 10-7
AAAA
TTTT
GGGG
CCCC
>>> #The file is close now. No need to use close() explicitly
CodeEx 10-8
81
Functions
Till now we have written small ‘disposable’ codes. It was a kind of ‘use and throw’
approach. This approach is good for learning. But these tiny programs are of little
use. Almost all the time we need to write bigger programs and for that, reuse of a
block of code is required. Thus, we need functions, a reusable block of code that is
independent of other codes of a program. Yes, it’s the same thing as print(), len(),
type(), etc. These are built-in functions in Python. Besides these, Python lets us
create our own.
Nevertheless, before diving further, you must remember the following key concepts.
These will guide you to properly define a function in the future.
Chapter 11: Functions
83
Chapter 11: Functions
you can use a local variable’s name outside the function body. If a local
variable shares the same name as a global variable, any code inside the
function will access the local variable. Any code outside will access the global
variable.
Do not get afraid if you can’t understand all the concepts properly. It’s normal for
beginners. You will understand all eventually after gaining experience with functions.
Till then just hold on and remember that the def keyword at starting, the colon (:) at the
end of the first line and the indented portion after that is insanely important in defining a function!
84
Chapter 11: Functions
calculate the adenine percentage of an input string and compare it with the cut-off. If
adenine % exceeds the cut-off, it will return True, else will return False.
Two main types of arguments in Python are positional arguments and keyword arguments.
Positional arguments need to be included in the order, regarding their corresponding
85
Chapter 11: Functions
parameters. See CodeEx 11-3. The function A_checker(), will consider its first
argument as the sequence value (the corresponding parameter is seq; line-3), and
the second argument as the cut-off % (the corresponding parameter is cutoff;
line-3). If we mess with the order, it will lead to an error. Look carefully at line-33;
AttributeError: ‘int’ object has no attribute ‘upper’. It
is showing that Python facing a problem in applying the upper() method on an
int object because upper() is a string method. Python channelized the first
argument through seq parameter which should be str but I put an int! This
feature is helpful and time-saving if you remember the positional values of arguments.
However, if your positional sense is not that much great, this feature could become a
boomerang to you. Instead, you can specify arguments by the name of their
corresponding parameters, which will then be termed keyword arguments. A
keyword argument is an argument passed to a function or method which is preceded by
a keyword or identifier (i.e., parameter name) and an assignment operator (=)CodeEx 11-4.
Here note that a function exactly takes the number of arguments specified at the
time of defining it (by using placeholder parameters). As an instance,
86
Chapter 11: Functions
dna_concat() takes exactly two argumentsCodeEx 11-5 and any sort of alteration to
that elicits an error. Carefully read the self-explanatory error messages in CodeEx
11-5.
87
Chapter 11: Functions
situation the default value gets automatically passed when the function is being
called, provided the user does not supersede the default value. You can specify a
default value to parameters by using the assignment operator (=) like you assign a value
to a variableCodeEx 11-6. From the CodeEx 11-6, you can see that
at_content()returns an output of varying precision according to your need and
if you do not mention your need for precision, it will round off the outcome to 4
decimal places according to its default value. Also, note that line-21 in CodeEx 11-6
does not elicit an error, whereas line-16 in CodeEx 11-5 elicits an error under similar
circumstances. This is the beauty of default arguments.
11.4. Docstrings
A docstring (documentation string) is a string literal that occurs as the first statement in a
function definition. Docstring is declared using triple quotes. Docstring is used to give
88
Chapter 11: Functions
the user a rational idea about what a function does. It is like comments in the code.
You can access a docstring using the __doc__ method or using the help
functionCodeEx 11-7. You also can use docstring over built-in functions like,
print(len.__doc__) or print(print.__doc__). Give it a try!
1 >>> #docstring
2 >>>
3 >>> def at_content(input_seq,round_to = 4):
4
5 ‘‘‘This function calculates AT content
6 It takes two args. First positional arg is the nucleotide
7 string (keyword: input_seq) and second one is the desired
8 rounding (keyword: round_to) with a default value of 4’’’
9
10 seq = input_seq.upper()
11 atgc = {i:[Link](i) for i in seq}
12 at = ((atgc[‘A’]+atgc[‘T’])/len(seq))*100
13 return round(at,round_to)
14
15 >>> #everything within ‘‘‘ ’’’ is a docstring
16 >>>
17 >>> #accessing the docstring by help()
18 >>> help(at_content)
19 Help on function at_content in module __main__:
20
21 at_content(input_seq, round_to=4)
22 This function calculates AT content
23 It takes two args. First positional arg is the
24 nucleotide string (keyword: input_seq)
25 and second one is the desired rounding
26 (keyword: round_to) with a default value of 4
27 >>>
28 >>> #accessing the raw docstring by __doc__(observe the
29 >>> #difference in output)
30 >>> print(at_content.__doc__)
31 This function calculates AT content
32 It takes two args. First positional arg is the
33 nucleotide string (keyword: input_seq)
34 and second one is the desired rounding
35 (keyword: round_to) with a default value of 4
36 >>>
CodeEx 11-7
89
Modules
I think I can safely assume now that you know how to create ‘your’ function and I
must congratulate you on this amazing achievement. Congratulations! With your
function, you can automate boring stuff! Write a function once and use it many
times. But remember, this use is restricted to the script where you created it. Outside
that script, your function is not available! However, what if you want to use your
function across other programs? Suppose you want to use the function you have
created, at_content(), across your upcoming programs and for that, you need
to create a module. Let’s begin.
Now, let me explain the structure of a module with an analogy. Imagine a library
building with multiple rooms. Each room has multiple book-racks full of books.
Now, if I compare a Python script with a book, then a book-rack will be a module,
library rooms will be packages, while the library itself becomes analogous with a
Python library.
Python has many super useful built-in general functions in its mainframe. So, when
we need them, we call them (e.g., print(), len(), etc). Apart from these, Python
has many ‘specialized functions’, which we can use anytime to make our life easier.
Chapter 12: Modules
To prevent Python from bloating, creators store these separately besides the
mainframe. They have organized these in structured directories, modules, and
packages. To use these, we must import these first by using the import keyword.
#atgc_cal.py module
#creating a dict
nucleotide = {'A':'Adenine',
'G':'Guanine',
'C':'Cytosine',
'T':'Thymine'}
#func:1
def at_cal(seq_in,round_to):
'''calculates AT content:
takes two arguments (para:seq=str &
round_to=int; output % of AT'''
seq = seq_in.lower()
at = (([Link]('a')+[Link]('t'))/len(seq))*100
return round(at,round_to)
#func:2
def gc_cal(seq_in,round_to):
'''calculates GC content:
takes two arguments (para:seq=str &
round_to=int; output % of GC'''
seq = seq_in.lower()
gc = (([Link]('g')+[Link]('c'))/len(seq))*100
return round(gc,round_to)
CodeEx 12-1
91
Chapter 12: Modules
import atgc_cal
CodeEx 12-2
#calling gc_content()
gc_content = gc_cal(‘aatgcatagatc’,2)
print(gc_content)
92
Chapter 12: Modules
import atgc_cal
at_content = atgc_cal.at_cal(‘aatgcatagatc’,2)
print(at_content)
gc_content = atgc_cal.gc_cal(‘aatgcatagatc’,4)
print(gc_content)
93
Chapter 12: Modules
import atgc_cal as a
at_content = a.at_cal(‘aatgcatagatc’,2)
print(at_content)
94
Chapter 12: Modules
import atgc_cal
print(dir(atgc_cal))
import atgc_cal as a
print(dir(a))
95
Chapter 12: Modules
See the CodeEx 12-8. Upon running, the program did not find the module because
the directories were different. Using Python’s built-in module sys can solve the
issue. See CodeEx 12-9 for the debugging. Now let me explain what happened in
CodeEx 12-9.
The list named path, a component of sys module, enlist directories which Python
checks for available modules. The goal of the program was to add the new module’s
directory to the list so that, when next time the program runs it finds the directory of
atgc_cal.py. In line-5 the program imports the sys module to use the list,
path. Line-6 checks whether the atgc_cal module’s directory path is in
Python’s checklist through the conditional statement. Line-7 ensure if it is not been
found, it must append the path to the list, path. Thus, the new directory path will
96
Chapter 12: Modules
be provisionally incorporated in Python’s default search list. The rest of the program
is already familiar to you.
If you find the mechanism too complicated don’t worry. Complicated concepts like
this will settle over time with experiences. For now, only remember the code and try
the CodeEx 12-10 and follow the output carefully.
‘‘‘try this code yourself and you will understand how sys
module and path list work’’’
import sys
#printing path
CodeEx 12-10
97
Chapter 12: Modules
>>> print(rand_seq)
>>>
>>> #choice()method is choosing from 4 characters of str
‘ATGC’
>>> #if you modify it with amino acid codes it will form
>>> #random peptide sequences.
>>> #here range dictates the length of output seq. change it
>>> #according to your need.
>>>
CodeEx 12-11
98
Regular Expression
Congratulations! You have made it through to the last chapter. You have learnt so
many new things, acquired so many new skills! You are now fit enough to start the
programming adventure on your own. Now in this last chapter, I am going to discuss
another ‘not so beginner’ skill, the regular expression! It will assist you to find complex
biological patterns.
13.1. re module
The Regular Expression, often abbreviated as RegEx, is a sequence of characters that
form a search pattern. The regular expression makes pattern searching a lot easier.
Though by no means it’s a tool for a newbie, for a biologist it’s a must-know. RegEx
comes as Python standard module re. So to access it, first, you have to
import it. Let’s explore the complex pattern searching by using re.
Chapter 13: Regular Expression
As you know finding RES for EcoRI is easyCodeEx 13-1. However, with RegEx, finding
the RES for AccB1I (and/or AasI) is as easy as EcoRI. See CodeEx 13-2.
res = ecor1(‘aaattgaattctggca’)
print(‘EcoR1 RES’s location:’,res)
A lot of things are there in CodeEx 13-2. Let me explain. Here, line-2 defines the
function accrb1() which takes two arguments. The first parameter is the
placeholder for the input sequence. The second parameter has a default value that is
the restriction sequence for Accb1I. Here the most important thing to notice is the
100
Chapter 13: Regular Expression
RES:GGCACC, at loc:3
>>>
CodeEx 13-2
2As RegEx uses lots of special characters, it is a good practice to convert any string to raw string
when the string is intended to use in RegEx. This step eliminates chances of creating unnecessary
confusion to Python.
101
Chapter 13: Regular Expression
matched sequence and its position, i.e., its index. However, these pieces of information
are not directly available. For that, you should call specific methods on the match-
object.
13.3. Metacharacters
With different combinations of metacharacters, we can generate complex search
patterns, which are very useful indeed in biology. Here I put a list of metacharacters
with brief description and examples regarding their uses (Table 13-1).
13.4. search()
The basic function of the re module is search(). I have discussed it in CodeEx
13-2. Its syntax is [Link](pattern, str to search in). It
searches the pattern within a string for a match and returns a match object if it finds a
match anywhere in the string. Otherwise, it returns None. However, there is a
downside of search(). It only returns the first occurrence of the match, if there is
over one matchCodeEx 13-3. To overcome this limitation, re has findall() method.
But before discussing the findall() we should discuss match object property
and methods available with it.
102
Chapter 13: Regular Expression
103
Chapter 13: Regular Expression
RES:GGCACC, at loc:3
>>>
>>> #the function only returns the first match though the input
>>> #sequence have a second match at index 8(GGCGCC)
>>>
CodeEx 13-3
start()& end(): These methods, respectively return the start index and end
index of the matched portion.
104
Chapter 13: Regular Expression
13.6. findall()
If there is over one match, findall() returns a list containing all non-
overlapping matches. Its syntax is [Link] (pattern, str to
search in). It does not return any match-object. However, it has a downside. It
just returns matches, not their indexes. For that, re has finditer() method.
13.7. finditer()
finditer() returns a sequence of match-objects, each containing data about
each matched pattern and its location. So, to do anything useful with the return value
of finditer(), we must iterate over it using a loop. Its syntax is re.
finditer(pattern, str to search in). See CodeEx 13-4.
105
Chapter 13: Regular Expression
13.8. split()
re has another very useful method split()which splits a string in each match
and returns a list containing all the resulting sub-strings as the list elementsCodeEx
13-6
. Its syntax is [Link](pattern, str to search in).
106
Chapter 13: Regular Expression
13.9. sub()
re method sub() replaces the matched portion of a string with the string of our
choiceCodeEx 13-7. Its syntax is [Link](pattern, replace with, str to
work on).
107
Micro Projects
1. Using the type() function find the types of these objects: ‘ATGCGC’;
564.09; 3; ‘4.9’; [‘Q’, ‘T’, ‘S’]; {‘Q’, ‘T’, ‘S’};
False; “45’; (‘Q’, ‘T’, ‘S’); {‘a’:1,‘b’:2,‘c’:3} and
“a5&gd”. If you find any error throughout the process then try to debug it.
2. Kindly check the following DNA sequence:
AtgTTTcGACgATGcACCAgCGGGCGATGAaCCAGTGACCCAcTTAGCgA
GTGAcCCATGCCAcGACGTCtGACttCTGACTaCGCaA. Now finds the
DNA’s length, GC-content, AT-content, complementary DNA sequence,
corresponding mRNA.
3. Create an executable program, GC-content calculator.
4. Convert the list, [‘atg’,‘gtc’,‘cga’], and string ‘atggtccga’ to
tuples.
5. Copy the data from the codon table in a column-wise manner to a .txt file and
name it [Link]. Using the file’s data create a dictionary that will have
codon: amino acid pairs as its items, where codons will act as keys while amino
acids as values.
6. Perform set union on the following sets: set_1 = {‘atg’, ‘gtc’,
‘cga’} & set_2 = {‘Q’, ‘R’, ‘S’}.
7. Create a program, protein’s molecular weight calculator, that will take a
polypeptide as an input and returns its molecular weight as the output. The
molecular weight of amino acids can be found over the internet.
Chapter 14: Micro Projects
8. With the write() method create a file at Desktop and writes a 20-nt sequence
of your choice into it. Now close the file. Again, open the file, append the data
with another 10-nt sequence as a new line and close the file. Reopen it and count
the AT content of the sequence data you have just created.
9. Define a function, which translates any given mRNA into its corresponding
polypeptide chain. Now calculates the mass of a polypeptide chain with the
function you developed earlier.
10. Define a function, which compares two homologous DNA strings and point out
the positions of point mutations along with the type of nucleotide change in each
position.
11. Generate a random nucleotide sequence of 10000-nt and store the data in a file
on your Desktop. Now with the executable interactive program GC-content
calculator you created use the file’s data, calculates its GC content, and store the
outcome in another file. Do necessary modifications in the GC content calculator
you have created so that it can accept a file as an input.
12. Define a function that converts a nucleotide string to its complementary string.
Also, define another function that changes the thymine (T) bases of a DNA string
109
Chapter 14: Micro Projects
to uracil (U) bases. With these two functions compose a module [Link].
Now generate a random 50-nt long DNA string using the random module and
convert the DNA to its complementary RNA using the [Link] module.
13. AasI’s RES is GACNNNN/NNGTC3. With this information in hand, define a
function that will act as an AasI’s RES Finder.
14. Autonomously replicating sequences (ARSs) function as replication origins in
Saccharomyces cerevisiae, and play an indispensable role in chromosome maintenance.
ARSs are usually ~100-200 bp long, and depend on an exact match, or very close
match, of an essential copy of an 11-base pair (bp) ARS consensus sequence
(ACS), 5’-WTTTAYRTTTW-3’4. Any mutations in ACS abolish ARS function.
Some ARSs also contain additional near-match ACSs replaceable for function.
However, substantial sequence conservation has been observed in the 3 bp on
either side of ACS, allowing for the identification of a 17-bp extended ACS
(EACS), 5’-WWWWTTTAYRTTTWGTT-3’. Here are two links to yeast ARS
elements (in FASTA):
[Link] or
[Link] Create an
executable program to check for any elusive ACS and/or elusive EACS sequence.
Your program should find the exact match and their respective positions in the
sequence. Also, the program should take a file as input and returns the result as a
file5.
110
It’s a New Beginning
I heartily congratulate you upon completing the book. You have done a
commendable job! It was not a simple task. Now, remember to practise a lot and
explore more books and resources to expand the horizon of your programming
knowledge. You are now fit to explore the field on your own. Start your voyage and
enjoy programming. Here, I have listed a few excellent books and online resources to
aid your knowledge. Please note, the list is not exhaustive.
Books
1. Bioinformatics Algorithms (2018) by Phillip Compeau & Pavel Pevzner, Active
Learning Publishers (3rd Ed); ISBN: 978-0-990-37463-3. It’s not only a book but
also a treasure trove for programmers interested in biology. As the name
suggests, it’s not a programming book. Authors have approached
algorithmically. A must-have book (preferably the eBook) for everybody who
wants to understand and apply programming in biology effectively. Not
designed for beginners. The reader should have beginner level knowledge in
any programming language to appreciate the beauty of this book. After
completing this book, you can access it.
2. Advanced Python for Biologists (2014) by Dr. Martin Jones; ISBN: 978-1-495-24437-
7. Another programming book by Dr. Jones written for biologists with
intermediate skill in programming. One of the best books to consult after
completing this book.
3. Effective Python Development for Biologists (2016) by Dr. Martin Jones; ISBN: 978-1-
539-10303-5. A book for intermediate level programmers with a biological
approach.
4. Learn Python in One Day and Learn It Well (2017) by Jamie Chan. A good, easy to
read general-purpose programming book for absolute beginners.
5. Introducing Python (2020) by Bill Lubanovic, O’Reilly Media (2nd Ed); ISBN: 978-1-
492-05136-7. A sort of general-purpose text cum reference python
programming text for beginners to advanced programmers. It’s a kind of
‘The book’ which must stay in your possession for any time referencing.
112
Chapter 15: It’s a New Beginning
Other resources
1. Rosalind: To make learning bioinformatics fun and easy, Rosalind, a platform
for learning bioinformatics through problem-solving, has been founded. This
platform also accompanied Bioinformatics Algorithms (2018) by Phillip Compeau
& Pavel Pevzner.
URL: [Link]
2. Python for Everybody (PY4E): This website is building a set of free materials,
lectures, book and assignments to help students learn how to program in
Python by Dr. Chuck.
URL: [Link]
3. Bioinformatics Algorithms: A website by Phillip Compeau & Pavel Pevzner
designed to give an overall view of the world of ‘Bioinformatics Algorithms’.
URL: [Link]
4. Coursera and edX: Two excellent MOOCs platform where you can get many
courses on Python programming spanning from beginner level to advanced
level. Free audit track is available with almost every course. These platforms
contain excellent courses like ‘Bioinformatics Specialization’ offered by
UCSanDiego, ‘Python for Everybody Specialization’ offered by the University of
Michigan, etc.
URL: [Link]
5. W3Schools and GeeksforGeeks: These are excellent educational websites for
learning to code online.
URL: [Link]
URL: [Link]
language/?ref=grb
113
Glossary
>>>: The default Python prompt of the interactive shell. Often seen for code
examples that can be executed interactively in the interpreter.
absolute path: A path that starts from the topmost directory in the file system.
algorithm: A general process for solving a category of problems.
argument: A value passed to a function (or method) when the function is called.
This value is assigned to the corresponding parameter in the function. There are two
types of arguments: positional arguments and keyword arguments.
assignment: A statement that assigns a value to a variable.
attribute: One of the named values associated with an object. It is referenced by
name using dotted expressions. For example, if an object o has an attribute a it
would be referenced as o.a.
bit: A bit (a portmanteau of binary digit) is the smallest unit of data in a computer.
A bit has a single binary value, either 0 or 1. It is the smallest building block of
storage. 8 bits together to make 1 byte.
block of code or suite: A code block is a piece of Python program text that is
executed as a unit. A code block is implemented using indentation.
body: The sequence of statements inside a function definition.
Boolean expression: An expression whose value is either True or False.
branch: One of the alternative sequences of statements in a conditional statement.
bug: An error in a program.
chained conditional: A conditional statement with a series of alternative branches.
class: A programmer-defined type. It is a template for creating user-defined objects.
Class definitions normally contain method definitions that operate on instances of
the class.
Glossary
code (short for source code): A term used to describe text/instructions that are
written using the syntax of a particular language by a coder/programmer.
comment: Information in a program that is meant for other programmers (or
anyone reading the source code) and does not affect the execution of the program.
compiled language: A programming language whose programs are typically
translated into machine language by a compiler before being executed (e.g., C,
Fortran, COBOL, etc).
compiler: A special program that processes statements written in a compiled
language and turns them into machine language.
compound statement: A statement that consists of a header and a body. The
header ends with a colon (:). The body is indented relative to the header.
concatenate: To join two operands end-to-end.
condition: The Boolean expression in a conditional statement that determines which
branch runs.
conditional expression: An expression that has one of two values, depending on a
condition.
conditional statement: A statement that controls the flow of execution depending
on some condition.
counter: A variable used to count something, usually initialized to zero and then
incremented.
data structure: A collection of related values, often organized in lists, dictionaries,
tuples, etc. Each data structure provides a particular way of organizing data so it can
be accessed efficiently, depending on your use case.
database: A file whose contents are organized like a dictionary with keys that
correspond to values.
debugging: The process of finding and correcting bugs.
decrement: An update that decreases the value of a variable.
default value: The value given to an optional parameter if no argument is provided.
115
Glossary
116
Glossary
file object: A value that represents an open file. It is also called a file-like object.
floating-point: A type that represents numbers with fractional parts.
floor division: An operator, denoted //, that divides two numbers and rounds
down (toward negative infinity) to an integer.
flow of execution: The order statements run in.
formal language: Any one of the languages that people have designed for specific
purposes, such as representing mathematical ideas or computer programs; all
programming languages are formal languages.
function call: A statement that runs a function. It consists of the function name
followed by an argument list in parentheses.
function definition: A statement that creates a new function, specifying its name,
parameters, and the statements it contains.
function: A named series of statements that returns some value to a caller.
Functions may or may not take arguments and may or may not produce a result.
global statement: A statement that declares a variable name global.
global variable: A variable defined outside a function. Global variables can be
accessed from any function.
header: The first line of a function definition.
high-level language: A programming language like Python that is designed to be
easy for humans to read and write.
IDLE: An Integrated Development Environment for Python. IDLE is a basic editor
and interpreter environment which ships with the standard distribution of Python.
immutable: The property of a sequence whose items cannot be changed. It is an
object with a fixed value. Immutable objects include numbers, strings, and tuples.
Such an object cannot be altered. A new object must be created if a different value
has to be stored.
import statement: A statement that reads a module file and creates a module object.
117
Glossary
118
Glossary
iterator: An object that can iterate through a sequence, but which does not provide
list operators and methods.
key: An object that appears in a dictionary as the first part of a key-value pair.
key-value pair: The representation of the mapping from a key to a value.
keyword argument: An argument that includes the name of the parameter as a
“keyword”. It preceded by an identifier with an assignment operator in a function
call.
keyword: A reserved word that is used to parse a program; you cannot use keywords
like if, def, and while as variable names.
list comprehension: A compact way to process all or part of the elements in a
sequence and return a list with the results. An expression with a for loop in square
brackets yields a new list.
list: A sequence of values. A built-in Python sequence.
literal value: A literal value is the value of a type that is to be used exactly as it is,
rather than as a variable. For examples, ‘ATGC’ or 456 are literals when they are
used exactly as it is without assigning a variable to these.
local variable: A variable defined inside a function. A local variable can only be used
inside its function.
logical operator: One of the operators that combine Boolean expressions: and, or,
and not.
loop: A part of a program that can run repeatedly.
low-level language: A programming language that is designed to be easy for a
computer to run; also called “machine language” or “assembly language”.
map: A processing pattern that traverses a sequence and performs an operation on
each element.
mapping: A relationship in which each element of one set corresponds to an
element of another set.
119
Glossary
method: A function that is defined inside a class body and that is associated with an
object and called using dot notation ([Link](argument)).
module object: A value created by an import statement that provides access to the
values defined in a module.
module: A file that contains a collection of related functions and other definitions.
It is an object that serves as an organizational unit of Python code.
modulus operator: An operator, denoted with a per cent sign (%), that works on
integers and returns the remainder when one number is divided by another.
natural language: Any one of the languages that people speak that evolved
naturally.
nested conditional: A conditional statement that appears in one of the branches of
another conditional statement.
nested list: A list that is an element of another list.
None: A special value returned by void functions.
object: Something a variable can refer to. Any data with the state (attributes or
value) and defined behaviour (methods), i.e., an object must have a type and a value.
object-oriented language: A language that provides features, such as programmer-
defined types and methods, that facilitate object-oriented programming.
object-oriented programming: A style of programming in which data and the
operations that manipulate it are organized into classes and methods.
operand: One of the values on which an operator operates.
operator: A special symbol that represents a simple computation like addition,
multiplication, or string concatenation.
optional argument: A function or method argument that is not required.
override: To replace a default value with an argument.
package: A Python module that can contain submodules or recursively, sub-
packages.
120
Glossary
121
Glossary
Pythonic: An idea or piece of code which closely follows the most common idioms
of the Python language, rather than implementing code using concepts common to
other languages.
reassignment: Assigning a new value to a variable that already exists.
reference: The association between a variable and its value.
relational operator: One of the operators that compares its operands: ==, !=, >, <,
>=, and <=.
relative path: A path that starts from the current directory.
return statement: A statement that causes a function to end immediately and return
to the caller.
return value: The result of a function. If a function call is used as an expression, the
return value is the value of the expression.
rubber duck debugging: Debugging by explaining your problem to an inanimate
object such as a rubber duck. Articulating the problem can help you solve it, even if
the rubber duck doesn’t know Python.
script mode: A way of using the Python interpreter to read code from a script and
run it.
script: A program stored in a file.
search: A pattern of traversal that stops when it finds what it is looking for.
semantic error: An error in a program that makes it do something other than what
the programmer intended.
semantics: The meaning of a program.
sequence: An ordered collection of values where each value is identified by an
integer index.
shape error: An error caused because a value has the wrong shape; that is, the
wrong type or size.
122
Glossary
shell: A program that allows users to type commands and then executes them by
starting other programs.
singleton: A list (or other sequences) with a single element.
slice: A part of a string specified by a range of indices.
slice: An object usually containing a portion of a sequence. A slice is created using
the subscript notation, [] with colons between numbers when several are given.
statement: A section of code that represents a command or action.
string: An immutable type that represents sequences of characters.
subject: The object a method is invoked on.
syntax error: An error in a program that makes it impossible to parse (and therefore
impossible to interpret).
syntax: The rules that govern the structure of a program.
temporary variable: A variable used to store an intermediate value in a complex
calculation.
text file: A file object able to read and write string objects.
text file: A sequence of characters stored in permanent storage like a hard drive.
traceback: A list of the functions that are executing, printed when an exception
occurs.
traverse: To iterate through the items in a sequence, performing a similar operation
on each.
tuple assignment: An assignment with a sequence on the right side and a tuple of
variables on the left. The right side is evaluated and then its elements are assigned to
the variables on the left.
tuple: An immutable sequence of elements.
type: The type of a Python object determines what kind of object it is; a category of
values (e.g., integers (type int), floating-point numbers (type float), and strings
(type str)).
123
Glossary
update: An assignment where the new value of the variable depends on the old.
value: One of the basic units of data, like a number or string, that a program
manipulates; An object that appears in a dictionary as the second part of a key-value
pair.
variable: A name that refers to a value.
void function: A function that always returns None.
Zen of Python: Listing of Python design principles and philosophies that help
understand and using the language. The listing can be found by typing import
this at the interactive prompt.
zip object: The result of calling a built-in function zip; an object that iterates
through a sequence of tuples.
124
About the author
Krishnendu pursued his bachelors in Zoology from the Presidency College, Kolkata,
his masters from the University of Calcutta, Kolkata, and his PhD from the Bose
Institute, Kolkata, India. Presently, he is working as an Assistant Professor in
Zoology, Jhargram Raj College, Jhargram since 2015. He is fascinated with evolution
and Python programming and is currently working in the field of computational
molecular evolution. He is also actively involved in teaching bioinformatics and
programming. Krishnendu strongly believes bioinformatics and computational
biology should be a major part of undergraduate and postgraduate programmes. He
also feels biology students and researchers must be familiar with programming
because, the basic understanding of programming is becoming increasingly necessary
to understand modern biology. Through this book, he wishes to guide all enthusiasts,
especially from the field of biology, to take baby steps in the world of programming.