0% found this document useful (0 votes)
24 views133 pages

Python for Biologists: Beginner's Guide

Basic Python Programming for Biologists is a beginner-friendly book designed to introduce programming concepts using Python, specifically tailored for those in the biological sciences. The book covers essential topics such as data types, operators, string manipulation, and file handling, with practical coding examples and exercises to reinforce learning. It emphasizes the importance of practice and problem-solving, encouraging readers to engage with additional resources for further challenges.

Uploaded by

Hyojung Yoon
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views133 pages

Python for Biologists: Beginner's Guide

Basic Python Programming for Biologists is a beginner-friendly book designed to introduce programming concepts using Python, specifically tailored for those in the biological sciences. The book covers essential topics such as data types, operators, string manipulation, and file handling, with practical coding examples and exercises to reinforce learning. It emphasizes the importance of practice and problem-solving, encouraging readers to engage with additional resources for further challenges.

Uploaded by

Hyojung Yoon
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basic Python Programming

for Biologists
A programming book for absolute beginners

Dr. Krishnendu Sinha


Basic Python Programming for Biologists © 2021 by Dr. Krishnendu Sinha is
licensed under CC BY-NC-SA 4.0
Edited by Dr. Nabanita Ghosh
ISBN: 978-93-5445-812-5 (eBook)
With love, dedicated to my family…
Contents
Hello World! ............................................................................ 1
0.1. Python .............................................................................................................................. 2
0.2. How to use this book..................................................................................................... 2
0.3. Acknowledgement .......................................................................................................... 3
0.4. Feedback .......................................................................................................................... 4
Getting Started.........................................................................5
1.1. Installing Python ............................................................................................................. 5
1.2. Accessing the Python Interpreter................................................................................. 5
1.3. Writing your FIRST code .............................................................................................. 5
1.4. Writing your FIRST program ....................................................................................... 6
Types, Variable & Operators ................................................ 12
2.1. Data ................................................................................................................................ 12
2.1.1. Value and type .............................................................................................. 12
2.2. Statement ....................................................................................................................... 13
2.3. Function and Argument .............................................................................................. 13
2.4. Comments ..................................................................................................................... 14
2.5. Object and Data Types ................................................................................................ 14
2.5.1. Object ............................................................................................................ 15
2.5.2. type() function ...................................................................................... 15
2.5.3. Type casting .................................................................................................. 17
2.6. Variables......................................................................................................................... 18
2.6.1. Python variables nomenclature rules ........................................................ 21
2.7. Basic operators .............................................................................................................. 22
2.8. Errors and Exceptions ................................................................................................. 23
2.8.1. Syntax errors ................................................................................................. 25
2.8.2. Exceptions .................................................................................................... 25
String Manipulation .............................................................. 26
3.1. Creating a string ............................................................................................................ 26
3.2. Special Characters ......................................................................................................... 26
3.3. String Characters’ Index .............................................................................................. 28
Contents

3.4. String Concatenation.................................................................................................... 29


3.5. Finding DNA Length .................................................................................................. 30
3.6. String Slicing .................................................................................................................. 30
3.7. ‘ATGC’ differs from ‘atgc’ ............................................................................... 30
3.8. replace() method ................................................................................................ 32
3.9. count() method ..................................................................................................... 33
3.10. find() method ...................................................................................................... 33
3.11. Raw String ................................................................................................................... 34
Interactive Program............................................................... 35
4.1. User input ...................................................................................................................... 35
4.2. DNA Length Calculator .............................................................................................. 36
4.3. Converting a Python script (.py) to an executable program (.exe) ................. 37
4.3.1. pyinstaller......................................................................................... 37
List ......................................................................................... 41
5.1. List indexing .................................................................................................................. 41
5.2. List mutability................................................................................................................ 42
5.2.1. append() and insert() method ..................................................... 42
5.2.2. remove() method and del keyword ................................................. 43
5.3. Slicing a list .................................................................................................................... 44
5.4. Reverse a list .................................................................................................................. 44
5.5. List joining ..................................................................................................................... 45
5.6. Sorting a list ................................................................................................................... 45
5.7. List length ...................................................................................................................... 45
5.8. Creating a list from a string ......................................................................................... 46
5.9. Creating a string from a list: join() ...................................................................... 46
5.10. Check items with in.................................................................................................. 47
5.11. zip() function ....................................................................................................... 47
5.12. List comprehension.................................................................................................... 49
5.13. Enumerate a list .......................................................................................................... 50
Tuple ...................................................................................... 51
6.1. tuple() constructor ............................................................................................... 51
6.2. Functions and operators on tuple .............................................................................. 52

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

11.4. Docstrings ................................................................................................................... 88


Modules ................................................................................. 90
12.1. Anatomy of module ................................................................................................... 90
12.2. Creating a module ...................................................................................................... 91
12.3. Using a module ........................................................................................................... 92
12.3.1. importing module ...................................................................................... 92
12.3.2. Calling functions from a module ............................................................. 93
12.3.3. import function from a module....................................................... 93
12.3.4. Re-naming a Module while importing .................................................... 94
12.4. Knowing components of a module ......................................................................... 94
12.5. sys module............................................................................................................... 95
12.6. Python’s built-in modules ......................................................................................... 97
Regular Expression ............................................................... 99
13.1. re module ................................................................................................................. 99
13.2. Finding restriction sites ........................................................................................... 100
13.3. Metacharacters .......................................................................................................... 102
13.4. search() ............................................................................................................... 102
13.5. Match object and its methods ............................................................................... 104
13.6. findall()........................................................................................................... 105
13.7. finditer() ........................................................................................................ 105
13.8. split() ................................................................................................................ 106
13.9. sub()...................................................................................................................... 107
Micro Projects ..................................................................... 108
It’s a New Beginning ........................................................... 111
15.1. Further references .................................................................................................... 111
15.1.1. Open Books.............................................................................................. 111
15.1.2. Books ......................................................................................................... 112
15.1.3. Other resources........................................................................................ 113
Glossary ......................................................................................... 114
About the author............................................................................ 125

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.

With these, I welcome you to the astonishing world of Python!


Chapter 0: Hello World!

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.

The non-profit organization Python Software Foundation ( [Link]


was formed in 2001, specifically to own Python-related Intellectual Property. The
Python Software Foundation is an independent non-profit organization that holds
the copyright on Python versions 2.1 and newer. The PSF’s mission is to advance
open-source technology related to the Python programming language and to
publicize the use of Python. All Python releases are Open Source, which means it
grants you all the rights to use, study, change, and share the software in modified and
unmodified form. In short, it’s completely free to use.

0.2. How to use this book


I have arranged the chapters in such a manner that skipping chapters will not be
logical. Each chapter has multiple contextual coding examples named CodeEx.
These are key to understanding syntax. Hence, kindly give special attention to these.

2
Chapter 0: Hello World!

Chapter 14 is dedicated to Micro Projects. These projects are arranged in order of


increasing complexity. After completing each chapter, you can visit Chapter 12 and
try to find is there any project you can solve with the knowledge you have acquired.
Solving problem is the key to understanding the concepts of programming. In this
regard, I strongly recommend visiting the Rosalind website
([Link] for facing more and more challenges. In
the Problem tab, you will find a vast selection of problems with varying complexity. So
after completing each chapter, along with Chapter 14 visit Rosalind to check your
concepts.

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.

Thanks to team-Rosalind <[Link] for creating


such an effective and beautiful free platform Rosalind, to aid in learning and teaching
bioinformatics through problem-solving.

3
Chapter 0: Hello World!

Thanks to Dr. Debnarayan Roy, Principal, Jhargram Raj College for his continued
patronage and encouragement.

Thanks to Saikat Sarkar, Associate Professor in Zoology, Singur Government


General Degree College for his persistent motivation.

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.

1.1. Installing Python


Installing Python into your PC is as simple as installing something like a media player!
Just go to [Link], the official Python website, where you can find the latest
version of Python (at the time of publishing this book it was version 3.9.5.). Download
and install it into your Figure 1-1.

1.2. Accessing the Python Interpreter


Python’s default implementation comes with the Integrated Development and Learning
Environment (IDLE). IDLE has two important features, an interactive interpreter (known
as Shell) and, a multi-window text editor. Mostly, I shall use the Shell to write codes
throughout the text. Under suitable circumstances, I shall use the text editor. Figure
1-2 illustrates how to access IDLE in a step-by-step manner.

1.3. Writing your FIRST code


Now, write your first code in the shell as belowCodeEx 1-1 and then hit enter. If you have
the same output as CodeEx 1-2, then congratulations, you have successfully written
your first line of code!
Chapter 1: Getting Started

>>> print(‘Hello World!’)


CodeEx 1-1

1 >>> print(‘Hello World!’)


2 Hello World!
3 >>>
CodeEx 1-2

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.

1.4. Writing your FIRST program


Now write your code in the text editor. Write “Hello World” and save it with a
.py extension. Henceforth, I shall call a file with a .py as a Python script. It’s permanent,
editable, and sharable! See Figure 1-4.

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

Figure 1-1. Step-by-step installation to Python for Windows.

7
Chapter 1: Getting Started

Click to start Shell

Type IDLE in search

>>> is the prompt of Python interactive interpreter,


Shell. It indicates that the interpreter is ready to take
next statement. It is only visible when Python is
running in interactive mode (e.g., in Shell).
Figure 1-2. Accessing IDLE Shell to use Python interpreter in interactive mode.

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

Figure 1-4. Creating Python script using IDLE text editor.

10
Chapter 1: Getting Started

Click on ‘Run Module’ or press F5

Program’s output in Shell

Figure 1-5. Running the newly created program, first_program.py.

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.

Value and type


Each data has its type and value. A value is one of the fundamental things, like a letter
or a number, which a program can manipulate. For example, ‘Hello World!’
in the first code is a value. Values belong to different data types (in short types). Often,
programmers use the words value and object, type, and class interchangeably. The value,
‘Hello World!’, belongs to the class string. An object is an instance of a class.
Say if the human is a class or type then we all are instances of that class. Consider
yourself as an object that belongs to the class human. This chapter is dedicated to
clarifying these and related concepts.
Chapter 2: Types, Variable & Operators

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.

2.3. Function and Argument


In the statement above, print() is a function. A function is a reusable block of code,
comprising a series of statements, which runs only upon calling (i.e., ‘using’) and
returns some data to the caller. Python has an array of built-in useful functions
according to our different needs. Also, we can define (i.e., ‘create’) a customized
function which I will discuss in the ‘Functions’ chapter. A function is analogous to a
machine, say like a coffee-maker, which takes roasted coffee beans as a starting
ingredient and returns a beautiful cup of coffee! Similarly, a function takes some
value as input to work on as the starting material and returns an output value.
Programmers use the word ‘passing’ to describe the value input process and the value
passed to a function is denoted as an argument (abbreviated as arg). In the first
code, the string object “Hello World!” was the argument for the function
print(). Syntactically, functions are followed by parentheses and we specify
arguments inside the parentheses: function(arg). Here note one thing, a
function could take more than one argument, passed to the function in a comma-
separated manner: function(arg_1, arg_2, arg_3, . . .,
arg_n). See CodeEx 2-1 for examples.

13
Chapter 2: Types, Variable & Operators

>>> #examples showing arguments passed to print() function


>>>
>>> print(‘ATTGC’) #string type argument ‘ATTGC’
ATTGC
>>> print(‘ATTGC’,9) #two args passed to print()
ATTGC 9
>>>
CodeEx 2-1

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!

>>> #it’s a comment


>>> #it’s another comment
>>> #anything starts with a # is a comment
CodeEx 2-2

2.5. Object and Data Types


In CodeEx 2-1, ‘ATTGC’, belongs to one of the several basic data types of Python,
string, and 9 belongs to the basic data type integer. In this section, you will get
accustomed to Python’s basic data types. A thorough understanding of data types is
important to learn to code. But first, I would like to present the concept of the object
to you.

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

Table 2-1. Basic Python data types


Type/
Name Mutability Examples
Class
String str Immutable ‘Hello World!’; “5”; ‘‘‘ATGC’’’

Integer int Immutable 5; 55; 546747

Float float Immutable 0.45; 5.0; 15.547

Dictionary dict Mutable {‘W’:‘Trp’,‘K’:‘Lys’,‘E’:‘Glu’}

List list Mutable [1,2,3]; [‘a’,‘b’,‘c’]; [1.2,5,‘a’]

Tuple tuple Immutable (1,2,3); (‘a’,‘b’,‘c’); (1.2,5,‘a’)

Set set Mutable {1,2,3};{‘a’,‘b’,‘c’};{1.2,5,‘a’}

Boolean bool Immutable True; False

>>> #knowing type of an object


>>>
>>> type(‘ATGC’)
<class ‘str’>
>>> type(5)
<class ‘int’>
>>> type(1.1)
<class ‘float’>
>>> type([1, 2, 3])
<class ‘list’>
>>> type({‘a’:‘x’, ‘b’:1})
<class ‘dict’>
>>> type((‘1.0’, 1, ‘a’))
<class ‘tuple’>
>>> type({1, 2, ‘a’})
<class ‘set’>
>>> type(True)
<class ‘bool’>
>>>
CodeEx 2-3

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.

The int() function takes in a float or an appropriate string and converts it to an


integerCodeEx 2-4. The float() function takes in an integer or an appropriate string
and changes it to a floatCodeEx 2-5. Similarly, the str() function converts suitable types
to a stringCodeEx 2-6.

>>> #type casting examples with int()


>>>
>>> #casting float into int, it removes digits after decimal
>>> #point
>>>
>>> int(4.678) #here 4.678 belongs to type float
4
>>>
>>> #casting str into int
>>>
>>> int(‘4’) #here ‘4’ is a str
4
>>>
>>> #but following conversions are forbidden
>>> #int(‘a string’) and int(‘4.678’)
>>> #here note 4.678(int) is not same as ‘4.678’(str)
>>>
>>> #try these yourself. You will get error messages.
>>> #try to get familiar with these errors.
>>> #errors are best friend of a programmer.
>>>
CodeEx 2-4

17
Chapter 2: Types, Variable & Operators

>>> # type casting examples with float()


>>>
>>> #casting int into float
>>>
>>> float(4)
4.0
>>>
>>> #casting str into float
>>>
>>> float(‘4’)
4.0
>>> float(‘4.678’)
4.678
>>>
>>> #but following conversions are forbidden
>>> #int(‘a string’)
>>>
>>> #try it yourself and observe the errors message carefully
>>>

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

>>> # type casting examples with str()


>>>
>>> #casting int into str
>>> str(4)
‘4’
>>>
>>> #casting float into str
>>> float(4.678)
‘4.678’
>>>
>>> #casting list into str
>>> str([1,‘a’,1.12])
“[1,‘a’,1.12]”
>>>
>>> #throughout the text you will see type casting in actions
>>> #also remember these examples are not exhaustive
>>>
CodeEx 2-6

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

>>> #variable = value; this is an assignment statement and (=)


>>> #is the assignment operator
>>>
>>> #initializing a few variables with zero value
>>>
>>> str_variable = ‘’ #initialized with empty string
>>> list_variable = [] # initialized with empty list
>>> dict_variable = {} #initialized with empty dict
>>> int_variable = 0 #initialized with int 0
>>>
>>> #initializing a few variables with some value
>>>
>>> var_1 = ‘ATGC’
>>> var_2 = 5
>>> var_3 = [1,2,3]
>>> var_4 = {‘A’:6,‘T’:6,‘G’:7,‘C’:7}
>>>
CodeEx 2-7

19
Chapter 2: Types, Variable & Operators

operatorCodeEx 2-7. Assignment operator is represented by an equal sign, (=). Here


remember, it has no relationship with mathematical equal operator. See CodeEx 2-7
for a few examples and CodeEx 2-8 to get an idea about the behaviour of variables.

>>> #reassignment and updating variable


>>>
>>> #x & y are variables
>>> x = 5
>>> y = 9
>>> y = x #reassigning y to x; y gets updated with x’s value
>>> print(y)
5
>>> print(x)
5
>>>
CodeEx 2-8

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
.

>>> #printing a dna string


>>>
>>> print(‘AATTCGATTCAGCTACTCAT’)
AATTCGATTCAGCTACTCAT
>>>
CodeEx 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.

>>> #assigning variable dna_1 to the string


>>>
>>> dna_1 = (‘AATTCGATTCAGCTACTCAT’)
>>>
>>> #now instead print(‘AATTCGATTCAGCTACTCAT’)
>>> #we can write
>>>
>>> print(dna_1)
AATTCGATTCAGCTACTCAT
>>>
>>> #henceforth dna_1 would hold the str value and is reusable
>>> #within this program
CodeEx 2-10

Python variables nomenclature rules


We can only name variables with:
1. lowercase letters (‘a’ through ‘z’),
2. uppercase letters (‘A’ through ‘Z’),
3. digits (0 through 9),
4. Underscore (_).
5. Variable names are case-sensitive; DNA_1, Dna_1, and dna_1 is different to
Python.
6. Variable names must begin with a letter or an underscore, NOT a digit.
7. Variable names cannot be one of the Python keywords. Type
help(‘keywords’) in the shell to get a full list of reserved keywords.

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

>>> ThisIsAVariable = 0 #CamelCaseNotation for variable naming


>>>
>>> this_is_a_variable = ‘’ #underscore for variable naming
>>>
>>> #however variable without a value elicits an error
>>>
>>> this_is_a_variable
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
this_is_a_variable
NameError: name 'this_is_a_variable' is not defined
>>>
CodeEx 2-11

2.7. Basic operators


You also can perform usual logical and mathematical operations on variables and literal
values with special symbols, known as operators. Table 2-3 listed a few of these
operators and CodeEx 2-12 provides few examples.

22
Chapter 2: Types, Variable & Operators

Table 2-3. List of basic operators in Python


Operator type Operator Syntax Meanings
< x<y Strictly less than
<= X<=y Less than or equal
Comparison > x>y Strictly greater than
>= x>=y Greater than or equal
== x==y Equal
!= x!=y Not equal
is x is y Object identity
Identity
is not X is not y Negate object identity
+ 7+3 Addition
- 7-3 Subtraction
* 7*3 Multiplication
Arithmetic / 7/3 Floating-point division
// 7//3 Floor division
% 7%3 Modulus (remainder)
** 7**3 Exponentiation
= x=y x=y
Assignment
+= x+=y x=x+y

2.8. Errors and Exceptions


Here I would like to introduce you to an important fact about programming. “Too
err is human”; programmers are no exception. Such inadvertent mistakes lead to
errors. So, don’t be afraid. Even pro-level programmers face this issue. Errors are

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.

>>> #assignment operators


>>> x = 3
>>> x += 7
>>> print(x)
10
>>>
>>> #arithmetic operators
>>> 7+3
10
>>> 7-3
4
>>> 7*3
21
>>> 7/3
2.3333333333333335
>>> 7//3
2
>>> 7%3
1
>>> 7**3
343
>>>
CodeEx 2-12

>>> #syntax error examples


>>>
>>> print(‘ATGC”)

SyntaxError: EOL while scanning string literal


>>>
>>> #error occurred as opening and closing quotes are different
>>>
>>> type(‘atgc’

SyntaxError: EOL while scanning string literal


>>>
>>> #error occurred as closing bracket missing
>>>
CodeEx 2-13

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.

>>> #exception examples


>>>
>>> this_is_a_variable
Traceback (most recent call last):
File “<pyshell#1>”, line 1, in <module>
this_is_a_variable
NameError: name ‘this_is_a_variable’ is not defined
>>>
>>> 10/0
Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
10/0
ZeroDivisionError: division by zero
>>>
>>> len(45)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
len(45)
TypeError: object of type 'int' has no len()
>>>
CodeEx 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.

3.1. Creating a string


Anything quoted in Python is a string and vice versa. Surrounding value with ‘single’ or
“double-quotes” or ‘‘‘triple quotes’’’ declares a string. However, remember to use only one
type of quotes to surround a string. Python does not permit the mixing of quotes. This
kind of action will lead to an error (line-5-20 of CodeEx 3-1). Also, Python considers
texts without quotes as variable names. If you do not assign a value to it, it raises an
error (line-22-31 of CodeEx 3-1). You can create multi-line strings triple quotesCodeEx
3-2
. Also, by typecasting with the help of str() function you can create a string type
by casting suitable types into a string.

3.2. Special Characters


To insert syntactically ‘illegal’ character in a string you can use a special character ‘backslash
(\)’ before that illegal characterCodeEx 3-3. Backslash is an ‘escape’ character. It helps to
escape from strict syntax rule.
Chapter 3: String Manipulation

1 >>> #strings are ALWAYS quoted


2 >>>
3 >>> #always use identical quotes
4 >>>
5 >>> dna_1 = “ATTCG” #or
6 >>> dna_2 = ‘ATTCG’ #but not
7 >>> dna_3 = “ATTCG’ #as mixing of quotes are prohibited
8 SyntaxError: EOL while scanning string literal
9 >>>
10 >>> #now printing these strings
11 >>>
12 >>> print(dna_1)
13 ATTCG
14 >>> print(dna_2)
15 ATTCG
16 >>> print(dna_3)
17 Traceback (most recent call last):
18 File "<pyshell#12>", line 1, in <module>
19 print(dna_3)
20 NameError: name 'dna_3' is not defined
21 >>>
22 >>> dna_4 = ATTCG
23 Traceback (most recent call last):
24 File "<pyshell#2>", line 1, in <module>
25 dna_4 = ATTCG
26 NameError: name 'ATTCG' is not defined
27 >>>
28 >>> #Python considers dna_4 as a variable by default as it
29 >>> #stays left to assignment operator. But this is not the
30 >>> #case for ATTCG. NameError occurred as Python treated
31 >>> #ATTCG as a variable as it is a text and devoid of quotes
32 >>>
CodeEx 3-1

>>> #string spanning multiple lines


>>>
>>> dna = ‘‘‘atgc
atcg
aatc’’’
>>> print(dna)
atgc
atcg
aatc
>>>
CodeEx 3-2

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.

1 >>> #string with illegal character and indentation


2 >>>
3 >>> dna = ‘That’s a DNA’
4 SyntaxError: invalid syntax
5 >>>
6 >>> dna = ‘That\’s a DNA’
7 >>> print(dna)
8 That's a DNA
9 >>>
10 >>> #creating indentation within string
11 >>>
12 >>> dna_a = ‘atcg\naatc\naatc’
13 >>> print(dna_a)
14 atcg
15 aatc
16 aatc
17 >>>
CodeEx 3-3

3.3. String Characters’ Index


In Python, the index of string characters starts at 0, not 1. That means the first
character of a string has an index ‘0’. Figure 3-1 shows the indexing pattern in
Python.

str A T T G C A A C G T

Index 0 1 2 3 4 5 6 7 8 9

Figure 3-1: Indexing string characters

28
Chapter 3: String Manipulation

3.4. String Concatenation


You can join two strings by using a ‘+’ operator. Python calls it String Concatenation.
Say, for example, imagine you have a dataset containing two exon sequences
generated from a splicing event. By using the string concatenation method, you can
join these to form an mRNACodeEx 3-4. Here note that you can concatenate a string
type with only another string type. Python does not allow the concatenation of strings
with other types (e.g., integers). To do so first you have to change the type of int to
strCodeEx 3-5.

>>> #string concatenation


>>>
>>> exon_1 = ‘augc’
>>> exon_2 = ‘cgau’
>>>
>>> #concatenating both exons and storing the resulting
>>> sequence in variables mrna
>>>
>>> mrna = exon_1 + exon_2
>>> print(mrna)
augccgau
>>>
CodeEx 3-4

>>> #str can’t be concatenated with other types


>>>
>>> dna = ‘atgc’
>>> length = 4
>>> print(‘seq:’+dna+‘,length:’+length)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
print('seq:'+dna+',length:'+length)
TypeError: can only concatenate str (not "int") to str
>>>
>>> #casting length (type int) to str and joining it with dna
>>>
>>> print(‘seq:’+dna+‘, length:’+str(length))
seq:atgc, length:4
>>>
CodeEx 3-5
29
Chapter 3: String Manipulation

3.5. Finding DNA Length


You can calculate the length of a string (i.e., the number of characters within the
string) by another Python’s in-built function, len(). This function takes a string as
an argument and returns its length in integer. len() function prints nothing on
screen like print(). Instead, it returns (note it does not print on screen, instead it
returns storable value) the valueCodeEx 3-6.

>>> #finding string length: len(‘any string’)


>>>
>>> dna = ‘atgc’ # here len() will take dna as an argument
>>> dna_len = len(dna) #assigning retuning value to dna_len
>>> print(dna_len)
4
>>>
CodeEx 3-6

3.6. String Slicing


You can easily slice a string at specific indexes. For extracting a specific fragment
from a DNA string, you can use Python’s slice tool. Python defines slice tool by
square brackets, [:]. It takes integers as the start and end index to use as reference
points for cutting. If not explicitly mentioned, by default 0 acts as the start index and
the length of the string, len(string) acts as the endpointCodeEx 3-7. Here you
should carefully note that the start index is inclusive while the end index is exclusive.
That means if you want to cut the substring ‘bcd’ from the string ‘abcdef’, use
the statement ‘abcdef’[1:4], not ‘abcdef’[1:3].

3.7. ‘ATGC’ differs from ‘atgc’


Python is highly case sensitive. It treats the uppercase letters differently from the
lowercase letters. So, be extra careful about the case of a string. However, you can

30
Chapter 3: String Manipulation

>>> #string slicing; [start(inclusive) : end(exclusive)]


>>>
>>> dna = ‘atgcttttcgca’
>>>
>>> #slicing substring ‘tttt’ from dna; for that
>>> #start index = 4, end index = 8 NOT 7
>>>
>>> dna_slice = dna[4:8]
>>> print(dna_slice)
‘tttt’
>>>
>>> # observe default start and end index
>>>
>>> dna_1 = dna[:8] #default start is index 0
‘atgctttt’
>>>
>>> dna_2 = dna[4:] #default end is the length of the string
‘ttttcgca’
>>>
CodeEx 3-7

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.

>>> #case changing with upper() and lower()


>>>
>>> dna = ‘ATTGC’
>>> dna_low = [Link]() #note the dot(.lower()) notation
>>> print(dna_low)
‘attgc’
>>> dna_up = dna_lower.upper() #using upper() method
>>> print(dna_up)
‘ATTGC’
>>> dna_up == dna #both are same
True
>>>
CodeEx 3-8

31
Chapter 3: String Manipulation

3.8. replace() method


replace() replaces a specified phrase within a string with another specified
phrase. It replaces all occurrences of the specified phrase if otherwise not restricted.
Say, I would like to replace the adenines of a DNA string with thymines.
replace() does the jobCodeEx 3-9. It takes at least two positional arguments separated
by a comma. The first argument shows what it should replace while the second
argument shows with which it should replace. However, there is an optional third
positional argument that specifies counts. This integer shows how many occurrences
of the specified phrase is to be replaced. By default, it is set to all occurrences. See
CodeEx 3-9 for clarifications .

>>> #syntax: [Link](oldvalue, newvalue, count)


>>>
>>> #replacing A with T
>>>
>>> dna = ‘AAAAATGC’
>>> dna_a2t = [Link](‘A’,‘T’)
>>> print(dna_a2t)
‘TTTTTTGC’
>>>
>>> #replacing with count
>>>
>>> dna_a2t_1 = [Link](‘A’,‘T’,1)
‘TAAAATGC’
>>> dna_a2t_2 = [Link](‘A’,‘T’,2)
‘TTAAATGC’
>>> dna_a2t_3 = [Link](‘A’,‘T’,3)
‘TTTAATGC’
>>>
>>> #replacing substring TGC of dna with AAA
>>>
>>> print([Link](‘TGC’,‘AAA’)
‘AAAAAAAA’
>>>
CodeEx 3-9

32
Chapter 3: String Manipulation

3.9. count() method


count() method takes a character or a substring/phrase as an argument and
returns the value of their total number of occurrencesCodeEx 3-10.

>>> #counting occurrences


>>>
>>> dna = ‘attgactgacg’
>>> t_count = [Link](‘t’) #counting thymine
>>> print(t_count)
3
>>> tga_count = [Link](‘tga’) #counting ‘tga’
>>> print(tga_count)
2
>>>
CodeEx 3-10

3.10. find() method


In CodeEx 3-11, ‘tga’ can be viewed as an imaginary sequence motif with
important implications. You can calculate the total number of occurrences of the
motif in each DNA sequence with the count(). Now, with find() you also can
pinpoint the location details of its occurrences within the DNA. find() takes the
substring/phrase as an argument and returns its indexCodeEx 3-11.

>>> #finding position of occurrences


>>>
>>> dna = ‘attgactgacg’
>>> tga_index = [Link](‘tga’) #findind index of ‘tga’ motif
>>> print(tga_index)
2
>>>
CodeEx 3-11

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.

3.11. Raw String


In Python, raw string is a normal string that is prefixed with an r. Raw string treats
special characters like a backslash (‘\’) as a literal character. In raw string, Python will
not treat ‘\’ as an escape characterCodeEx 3-12. In short, within raw string special
characters has no speciality.

>>> #raw string


>>>
>>> print(‘atta\ntaat’) #string with new line character
atta
taat
>>> print(r‘atta\ntaat’) #raw string treats \n as a literal
atta\ntaat
>>> print(‘atta\ttaat’) #string with tab character
atta taat
>>> print(r‘atta\ttaat’) #raw string treats \t as a literal
atta\ttaat
>>> print(‘\‘ATGC\’’) #escape character \
‘ATGC’
>>>
>>> #raw string treats escape character \ as literal
>>> print(r‘\‘ATGC\’’)
\‘ATGC\’
>>>
CodeEx 3-12

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!

4.1. User input


Python has a built-in function, input()CodeEx 4-1. When being called, it prompts the
user to give her input. It takes user input as an argument and supplies it to the
program as a string. input() also allows incorporation messages to guide users
properly so that, the program gets an error-free input. Just put a string as an
argument in the input() and input() will use it as a prompted message to
guide users ( see line 4 & 5; CodeEx 4-1).

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

4.2. DNA Length Calculator


Now imagine, daily you have to calculate lots of DNA length as a part of your lab
work. For a small sequence, it is ok to go with the ‘eyeball’ method. But, for a large
sequence, it becomes a humongous job. Here, a DNA Length Calculator comes in
handy. Let’s make one! From the last chapter, you already know how to calculate the
DNA length of a string. Here I am just adding the interactive fragment of the
codeCodeEx 4-2.

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.

>>> #DNA Length Calculator


>>>
>>> #part 1: the interactive part of the code
>>>
>>> user_dna = input(‘provide DNA seq:’)
provide DNA seq: attgacatgacttgatc
>>>
>>> #part 2: the core mechanistic part of the code
>>>
>>> dna_len = len(user_dna) #user_dna supplied from part 1
>>> print(‘length of the given sequence is:’, dna_len, ‘bp’)
length of the given sequence is: 17 bp
>>>
CodeEx 4-2

36
Chapter 4: Interactive Program

4.3. Converting a Python script (.py) to an executable


program (.exe)
You have just made a very useful calculator. But it’s only useful to you as you are a
Python programmer. But for those who are not familiar with programming, it will be
very difficult to use the calculator. To use it the user must know the basics of
running a Python script and they must have Python installed in their system. But
with a few steps, you can make the program accessible for all. Just convert the
Python script (.py) to an executable program (.exe). Windows will run the .exe
without having Python pre-installed. A user need not have any sort of programming
knowledge to run a .exe file.

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.

Clicking ‘Save as’ opens


a pop-up window; there,
saving it as [Link]

This line showing the path


DNA string supplied to the to that directory where the
program when it prompted program script is located
with the message

Figure 4-1: Guide to saving the program as a Python script ([Link]) and running it.

38
Chapter 4: Interactive Program

a
b

Figure 4-2: Guide to install pyinstaller.

Figure 4-3. Converting Python script to an executable program.

39
Chapter 4: Interactive Program

Figure 4-4. Running the executable 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.

5.1. List indexing


A list is an ordered data structure. That means list elements maintain the order of
incorporation, have specific indexes and are accessible by their indexes. The first
element has index 0, the second element has index 1 and so on, same as string
indexing, Figure 5-1. You can also access these elements from last where the last element
has an index of -1, the penultimate has an index of -2 and so onFigure 5-1. See
CodeEx 5-2 for better understanding.
Chapter 5: List

>>> #[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

>>> #accessing list elements


>>>
>>> dna_list = [‘ATGC’,‘ATTG’,‘GTAC’]
>>> first_elm = dna_list[0]
>>> second_elm = dna_list[1]
>>> last_elm = dna_list[-1]
>>> print(first_elm, second_elm, last_elm)
ATGC ATTG GTAC
>>>
CodeEx 5-2

5.2. List mutability


The mutability of a list allows us to replace and/or remove elements from the list.

append() and insert() method


append() method adds an item to the end of a list whereas, with the insert()
method you can insert an item at any desirable positionCodeEx 5-3. append() takes
list [ ‘A’ ‘T’ ‘G’ ‘C’ ]
Index 0 1 2 3
Index -4 -3 -2 -1
Figure 5-1: List element indexing.

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.

>>> #list mutability


>>>
>>> #append an item
>>>
>>> dna_list = [‘ATGC’,‘ATTG’,‘GTAC’]
>>> dna_list.append(‘AAAA’) #appending dna_list with ‘AAAA’
>>> print(dna_list)
[‘ATGC’, ‘ATTG’, ‘GTAC’, ‘AAAA’]
>>>
>>> #insert an item
>>>
>>> dna_list.insert(1,‘TTTT’)
>>> print(dna_list)
[‘ATGC’, ‘TTTT’, ‘ATTG’, ‘GTAC’, ‘AAAA’]
>>>
CodeEx 5-3

remove() method and del keyword


remove() method removes the first item, whose value is equal to the argument
supplied, from the list. del keyword deletes item(s) from a listCodeEx 5-4.

>>> #list mutability


>>>
>>> dna_list = [‘AAA’,‘TTT’,‘GGG’,‘CCC’,‘TTT’] #remove an item
>>> dna_list.remove(‘TTT’)
>>> print(dna_list)
[‘AAA’, ‘GGG’, ‘CCC’, ‘TTT’]
>>>
>>> del dna_list[1] #delete item with index 1, i.e., ‘GGG’
>>> print(dna_list)
[‘AAA’, ‘CCC’, ‘TTT’]
>>>
CodeEx 5-4

43
Chapter 5: List

5.3. Slicing a list


Like a string, you can easily slice a list at specific indexes for extracting a specific set
of elements from it with the help of Python’s slice tool, [:]. It takes a start and an
end index to use as slicing points. Here the start index is inclusive and the end index is
exclusive. You can store sliced items like a new list. See CodeEx 5-5 for a better
understanding.

>>> #list slicing


>>>
>>> dna_list = [‘AAA’,‘TTT’,‘GGG’,‘CCC’,‘TTT’]
>>>
>>> #extracting items with index 1 & 2 and saving it
>>> # as a new list
>>>
>>> new_list = dna_list[1:3]
>>> print(new_list)
['TTT', 'GGG']
>>>
CodeEx 5-5

5.4. Reverse a list


reverse() method reverses the order of list elements. This method does not
return anything. It makes changes in the original list. See CodeEx 5-6.

>>> #list reversal


>>>
>>> dna_list = [‘AAA’,‘TTT’,‘GGG’,‘CCC’,‘TTT’]
>>> dna_list.reverse()
>>> print(dna_list)
[‘TTT’, ‘CCC’, ‘GGG’, ‘TTT’, ‘AAA’]
>>>

CodeEx 5-6

44
Chapter 5: List

5.5. List joining


More than one list can be joined with the help of + operatorCodeEx 5-7. The syntax is
like string concatenation.

>>> #joining two lists


>>>
>>> list_1 = [‘AAA’,‘TTT’,‘GGG’]
>>> list_2 = [1,2,3]
>>> joined_list = list_1 + list_2
>>> print(joined_list)
[‘AAA’, ‘TTT’, ‘GGG’, 1, 2, 3]
>>>
CodeEx 5-7

5.6. Sorting a list


You can sort list elements by using the sort() method. After sorting, Python will
assign elements with new indexes according to their new orderCodeEx 5-8.

>>> #sorting strings


>>>
>>> str_list = [‘k’,‘a’,‘f’,‘b’,‘n’]
>>> str_list.sort()
>>> print(str_list)
[‘a’, ‘b’, ‘f’, ‘k’, ‘n’]
>>>
>>> int_list = [2, 5, 1]
>>> int_list.sort()
>>> print(int_list)
[1, 2, 5]
>>>
CodeEx 5-8

5.7. List length


The length of a list shows its total number of items. len() function takes a list as
its argument and returns the length of the listCodeEx 5-9.

45
Chapter 5: List

>>> #list length


>>>
>>> dna_list = [‘AAA’,‘TTT’,‘GGG’,‘CCC’,‘TTT’]
>>> length = len(dna_list)
>>> print(length)
5
>>>
CodeEx 5-9

5.8. Creating a list from a string


You can convert strings to list by the type constructor, list(), which takes the
string as an argument. It returns a list by converting the characters of the string to
the elements of the list.
Python also has another method, split(), which chops a string into a list by some
separator already present in the string (e.g., \n can act as a separator). split()
takes separator as an argument. Carefully follow CodeEx 5-10.

>>> s = ‘string’ #str to list


>>> l = list(s) #using list constructor
>>> print(l)
[‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’]
>>>
>>> triplet = ‘AAA,TTT,GGG,CCC’
>>> triplet_list = [Link](‘,’)#using comma as separator
>>> print(triplet_list)
[‘AAA’,‘TTT’,‘GGG’,‘CCC’]
>>>
CodeEx 5-10

5.9. Creating a string from a list: join()


join() method takes all items of an iterable sequence of strings (e.g., a
homogeneous list whose elements are strings) as its argument and joins them into
one string. The string must be specified as the separator. The separator might be an

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.

>>> #list to string: ‘separator’.join(iterable)


>>>
>>> triplet = [‘AAA’,‘TTT’,‘GGG’,‘CCC’]
>>> print(‘,’.join(triplet)) #comma (‘,’) as separator
AAA, TTT, GGG, CCC
>>> print(‘’.join(triplet)) #empty string (‘’) as separator
AAATTTGGGCCC
>>> print(‘@’.join(triplet)) #@ as separator
AAA@TTT@GGG@CCC
>>>
CodeEx 5-11

5.10. Check items with in


The in keyword creates a Boolean condition. You can check the existence of an
item in a list with in keywordCodeEx 5-12.

>>> #checking whether a value is in triplet


>>>
>>> triplet = [‘AAA’,‘TTT’,‘GGG’,‘CCC’]
>>> ‘TTT’ in triplet
True
>>> ‘ttt’ in triplet
False
>>>
CodeEx 5-12

5.11. zip() function


With the zip() function, it is possible to iterate over more than one list
simultaneously. Though this function is not a typical ‘beginners’ tool, it is worth
mentioning here because of its utility. I am suggesting a revisit of this and the next

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
.

>>> #creating dictionary by taking input from two lists


>>>
>>> single_letter = [‘Q’, ‘T’, ‘A’, ‘P’]
>>> three_letter = [‘Gln’, ‘Thr’, ‘Ala’, ‘Pro’]
>>> z = zip(single_letter, three_letter)
>>> type(z)
<class ‘zip’>
>>>
>>> #unzipping
>>>
>>> amino_dict = dict(z) # unzipping with dict() constructor
>>> print(amino_dict)
{‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>>
CodeEx 5-13

48
Chapter 5: List

>>> #working logic of zip()


>>>
>>> z = zip(‘abcd’, ‘ABCD’, ‘xyz’)
>>> type(z)
<class ‘zip’>
>>> tuple(z)
((‘a’, ‘A’, ‘x’), (‘b’, ‘B’, ‘y’), (‘c’, ‘C’, ‘z’))
>>>
>>> #table showing iteration sequence
Iterable Value with Value with Value with Value with
object index 0 index 1 index 2 index 3
1 ‘a’ ‘b’ ‘c’ ‘d’
2 ‘A’ ‘B’ ‘C’ ‘D’
3 ‘x’ ‘y’ ‘z’
zip(1,2,3) (‘a’,‘A’,‘x’) (‘b’,‘B’,‘y’) (‘c’,‘C’,‘z’)
>>>
CodeEx 5-14

5.12. List comprehension


List comprehensions provide a short and concise syntax to construct a new list based
on the values of an iterable object (e.g., str, list etc.)CodeEx 5-15.

>>> #list comprehension


>>>
>>> #newlist = [elmnt for elmnt in iterable if condtn==True]
>>>
>>> dnt = [‘at’, ‘aa’, ‘gc’, ‘ga’, ‘tt’, ‘at’, ‘cg’, ‘ac’]
>>> dnt_a = [ i for i in dnt if ‘a’ in i]
[‘at’, ‘aa’, ‘ga’, ‘at’, ‘cg’, ‘ac’]
>>>
>>> #made newlist dnt_a by picking only items with ‘a’ from
>>> #oldlist, dnt
>>>
CodeEx 5-15

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.

>>> codon_lst = [‘ACUT’, ‘AGAR’, ‘AGCS’]


>>>
>>> #for each item in codon_lst the last character indicates
>>> #an amino acid where first three characters indicates
>>> #respective triplet codon. Now making a pair value list
>>>
>>> codon_lst_pv = [(i[:3],i[-1]) for i in codon_lst]
>>> print(codon_lst_pv)
[(‘ACU’, ‘T’), (‘AGA’, ‘R’), (‘AGC’, ‘S’)]
>>>
CodeEx 5-16

5.13. Enumerate a list


enumerate() method adds a counter to an iterable and returns it in the form of
an enumerate object. You can use this enumerate object directly in for loops or can
convert it into a list of tuples using list(). Just remember, enumerate() takes
two arguments. The first positional argument is the iterable object and the second
one is the starting counter, which is by default set to zeroCodeEx 5-17.

>>> #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

6.1. tuple() constructor


tuple() constructor can start a tuple or convert other suitable data types to
tupleCodeEx 6-2. It works similarly to the list constructor discussed in the last chapter.
Chapter 6: Tuple

>>> #tuple from string


>>>
>>> aa = ‘QTSA’
>>> aa_tuple = tuple(aa)
>>> print(aa_tuple)
(‘Q’, ‘T’, ‘S’, ‘A’)
>>>
>>> #list to tuple
>>>
>>> list2tuple = tuple([‘Q’, ‘T’, ‘S’, ‘A’])
>>> print(list2tuple)
(‘Q’, ‘T’, ‘S’, ‘A’)
>>>
CodeEx 6-2

6.2. Functions and operators on tuple


In CodeEx 6-3, find a few useful functions and operators which you can use with
tuple. Just go through it and try it yourself. It’s self-explanatory but not exhaustive.

>>> #concatenation of tuples using (+) operator


>>> t_1 = (‘Q’,‘T’)
>>> t_2 = (‘S’,‘A’)
>>> t_3 = t_1 + t_2
>>> print(t_3)
(‘Q’, ‘T’, ‘S’, ‘A’)
>>> len(t_1) #getting length of tuple by len()
2
>>> t_3[1] #access tuple’s item by referring its index
‘T’
>>> t_3.count(‘Q’) #count tuple items by count() method
1
>>>
CodeEx 6-3

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 is declared using curly brackets containing key-value pairs in a comma-


separated manner. See CodeEx 7-1 for further clarification.
Chapter 7: Dictionary

>>> #{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

7.1. dict() constructor


Also, you can build a dictionary from key-value sequences (paired value sequences) using
dict() constructorCodeEx 7-2.

>>> #paired value sequences to dict


>>>
>>> #aa is a paired value list
>>>
>>> aa = [(‘Q’, ‘Gln’), (‘T’, ‘Thr’), (‘A’, ‘Ala’)]
>>> aa_dict = dict(aa)
>>> print(aa_dict)
{‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’}
>>>

CodeEx 7-2

7.2. Dictionary keys


Keys help us to handle dictionary items in several ways as you can see in CodeEx 7-3.

7.3. Using in keyword and get() method on a dictionary


To check whether a key is present in a dictionary you can use in keyword that gives
a Boolean outcome. As an output, True means the key is present in the dictionary

54
Chapter 7: Dictionary

>>> aa_dict = {‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’}


>>>
>>> #adding new item (with key ‘P’ and value ‘Pro’ in aa_dict)
>>> aa_dict[‘P’] = ‘Pro’
>>> aa_dict
{‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>>
>>> #removing the value (‘Thr’)
>>> del(aa_dict[‘T’])
>>> aa_dict
{‘Q’: ‘Gln’, ‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>>
>>> #changing the value (‘Ala’ to ‘Alanine’)
>>> aa_dict[‘A’] = ‘Alanine’
>>> aa_dict
{‘Q’: ‘Gln’, ‘A’: ‘Alanine’, ‘P’: ‘Pro’}
>>>
CodeEx 7-3

whereas False indicates its absence. Also, you can access the value mapped with
the key with get() methodCodeEx 7-4.

>>> #finding a key with value


>>>
>>> aa_dict = {‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>> ‘T’ in aa_dict #using in keyword
True
>>> ‘S’ in aa_dict
Flase
>>> aa_dict.get(‘T’) #using get() method
‘Thr’
>>>
CodeEx 7-4

7.4. Extract all keys & values, or both


By using dictionary methods keys(), values() and items() you can extract
all the keys, values, and key-value pairs respectively from a dictionary.
The keys() method returns a dictionary view object. The view object (<class

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

>>> #keys(), values() & items()


>>>
>>> aa_dict = {‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>>
>>> #getting all keys from aa_dict
>>>
>>> key = aa_dict.keys()
>>> print(key)
dict_keys([‘Q’, ‘T’, ‘A’, ‘P’])
>>> type(key)
<class ‘dict_keys’>
>>>
>>> #passing the output through list()(though not necessary)
>>>
>>> list(key)
[‘Q’, ‘T’, ‘A’, ‘P’]
>>>
>>> #similarly
>>>
>>> list(aa_dict.values())
[‘Gln’, ‘Thr’, ‘Ala’, ‘Pro’]
>>>
>>> list(aa_dict.items())
[(‘Q’, ‘Gln’), (‘T’, ‘Thr’), (‘A’, ‘Ala’), (‘P’, ‘Pro’)]
>>>
CodeEx 7-5

7.5. Getting the length of a dictionary


Length of a dictionary shows the total number of items of the dictionary and with
the len() function you can get that. len() takes a dictionary as its argumentCodeEx
7-6
.

56
Chapter 7: Dictionary

>>> #getting dict length


>>>
>>> aa_dict = {‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’}
>>> print(len(aa_dict))
3
>>>
CodeEx 7-6

7.6. Update and merge dictionaries


Python 3.9 has added two new operators to its built-in dictionary class: update (|=)
and merge (|). Update operator (|=) update the dictionary left to it with the object
from its right. which may be either a mapping pair (e.g., another dictionary) or an
iterable of key/value pairs (e.g., a list of tuples where each tuple has two comma
separated items; [(1,2),(3,4)]). Whereas, merge operator (|) creates a new
dictionary with the merged keys and values of both operands. Here, both operands
must be dictionariesCodeEx 7-7.
>>> #merging and updating dictionaries
>>>
>>> aa_dict_1 = {‘Q’: ‘Gln’, ‘T’: ‘Thr’}
>>> aa_dict_2 = {‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>>
>>> #creating a new aa_dict_3 by merging aa_dict_1 with
>>> #aa_dict_2
>>>
>>> aa_dict_3 = aa_dict_1|aa_dict_2
>>> aa_dict_3
{‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>>
>>> #updating aa_dict_1 with aa_dict_2
>>>
>>> aa_dict_1 |= aa_dict_2
>>> aa_dict_1
{‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>> aa_dict_2
{‘A’: ‘Ala’, ‘P’: ‘Pro’}
>>>
CodeEx 7-7

57
Chapter 7: Dictionary

7.7. Dictionary comprehension


Like all other comprehensions, dictionary comprehensions in Python also provide a
short and concise way to construct a new dictionary based on the values of an
iterable paired value object (e.g., [(1,2),(3,4)]). In CodeEx 7-8, I have used
the paired value list, aa, to create a codon dictionary. The dictionary will hold a
codon as a key, and its respective amino acid as a value. Here is another instance
where dictionary comprehension could elegantly replace the multi-line code which
you could write to know the nucleotide count for any sequenceCodeEx 7-9. From the
two-line code, you can make an elegant executable program that will help to calculate
nucleotide frequencies (i.e., percentage of each nucleotide in an input sequence).

>>> #list comprehension


>>> #from pair value list creating an aa dictionary
>>>
>>> aa = [(‘Q’, ‘Gln’), (‘T’, ‘Thr’), (‘A’, ‘Ala’)]
>>> aa_dict = {a: aaa for a, aaa in aa}
>>> print(aa_dict)
{‘Q’: ‘Gln’, ‘T’: ‘Thr’, ‘A’: ‘Ala’}
>>>
CodeEx 7-8

>>> #atgc count


>>> dna = 'aggctgacttgacaccagtcgacatcgacgtac'
>>> atgc_count = {base:[Link](base) for base in dna}
>>> print(atgc_count)
{‘a’: 9, ‘g’: 8, ‘c’: 10, ‘t’: 6}
>>>
>>> #even better
>>> atgc = {[Link]():[Link](base) for base in dna}
>>> atgc_count
{‘A’: 9, ‘G’: 8, ‘C’: 10, ‘T’: 6}
>>>

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

8.1. set() constructor


set() constructor works the same as the list or tuple constructor. It can start a set
or convert other suitable data types to setCodeEx 8-2.

8.2. Functions and operators on set


In CodeEx 8-3, find a few useful functions and operators which you can use with the
set. Just go through it and try those codes yourself. Remember, these are not
exhaustive.
Chapter 8: Set

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

>>> #set union using pipe character (|) operator


>>>
>>> s_1 = {‘Q’,‘T’}
>>> s_2 = {‘S’,‘A’}
>>> s_3 = s_1 | s_2
>>> print(s_3)
(‘Q’, ‘T’, ‘S’, ‘A’)
>>>
>>> #getting length of set by len()
>>>
>>> len(s_1)
2
>>> len(s_3)
4
>>>
CodeEx 8-3

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.

A conditional statement is composed of a Boolean expression that returns True or


False. If it returns True, then a branch, a block of code, get executed and if it
returns False, any other code block gets executed or the execution halts.
Nevertheless, do not get lost in words. Examples will make you understand the
working principle of the conditional statements.

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

>>> ##composing a few simple conditions


>>>
>>>5>3 #Is 5 greater than 3?
True
>>> 3>5 #Is 3 greater than 5?
False
>>> # Is length of ‘atgc’ greater or equal to length of ‘atc’?
>>> len(‘atgc’) >= len(‘atc’)
True
>>> # Is length of ‘atgc’ less or equal to the length of int 5?
>>> len(‘atgc) <= 5
True
>>> # Is length of ‘atgc’ equal to int 4?
>>> len (‘atgc’) == 4
True
>>> # Is the value of ‘atgc’ equal to the value of ‘atGc’?
>>> ‘atgc’ == ‘atGc’
False
>>> # Is the value of ‘atgc’ not equal to the value of ‘atGc’?
>>> ‘atgc’ != ‘atGc’
True
>>> # Is ‘atgc’ in upper case?
>>> ‘atgc’.isupper()
False
>>> # Is ‘atgc’ in lower case?
>>> ‘[Link]()
True
>>> # Is str ‘atgc’ starts with letter ‘a’?
>>> ‘atgc’.startswith(‘a’)
True
>>> # Is str ‘atgc’ ends with letter ‘c’?
>>> ‘atgc’.endswith (‘c’)
True
>>>
>>> ##a few complex conditions
>>>
>>> #Is both operands True?
>>> 5>3 and 3>5
False
>>> #Is any one operand True?
>>> 5>3 or 3>5
True
>>>

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')

============= RESTART: C:/Users/Desktop/[Link] ==========


x = 4
x is positive
y is greater than 1
>>>
>>> #running the script again and putting 0 as input
x = 0
>>> #no output as condition in line 4 becomes False
>>>
CodeEx 9-2

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’)

============= RESTART: C:/Users/Desktop/[Link] ==========


x = 1
x is positive
>>>
>>> #running the script again and putting 0 as input
x = 0
x is Zero
>>>
>>> # running the script again and putting -1 as input
x = -1
x is negative
>>>
CodeEx 9-3

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.

Now observe the flow chart (Figure 9-1) of a program amino_acid_decoder.


The program takes single-letter amino acid code as user inputs and outputs
corresponding amino acid name and three-letter amino acid codeCodeEx 9-4. This
program is relatively buggy! For example, what if a user gives an integer input of
anything other than a single letter amino acid code? The program will crash! So, it
needs debugging and you will find the solution at the end of this chapter.

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!’’’

============= RESTART: C:/Users/Desktop/[Link] ==


Enter single-letter amino acid code:n
N stands for Asparagine(Asn)
CodeEx 9-4

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!

1 >>> #structure of while loop


2 >>> #initiating loop counter x with value 5
3 >>> x = 3
4 >>> while x >=0:
5 print(x)
6 x -= 1
7
8 3
9 2
10 1
11 0
12 >>>
13 >>> #you can call the program as the ‘countdown’
14 >>>
CodeEx 9-5

1 >>> #converting countdown to an infinite loop just by


2 >>> #eliminating line 6 of CodeEx 9-5
3 >>> #run the below code and see what happens!
4 >>>
5 >>> x = 5
6 >>> while x >=0:
7 print(x)
8 …

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.

1 >>> #structure of for loop


2 >>> #using a list [0,1,2,3,4] as an iterable object
3 >>>
4 >>> for item in [0,1,2,3,4]:
5 print(“It’s ”,item)
6
7 It’s 0
8 It’s 1
9 It’s 2
10 It’s 3
11 It’s 4
12 >>>
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.

continue and break


continue and break statements are also control statements that are used to
control the flow within a loop. Based on certain condition, continue statement
stops a current iteration and jumps to the next. While break statement based on
some condition can pretermit a loop, even if the loop condition remains True or it
has finished its iteration. Follow CodeEx 9-9. Line-4 setting the condition for

68
Chapter 9: Conditional Statements

>>> #extracting amino acids from small peptide chain


>>>
>>> peptide = ‘QHILK’
>>> for aa in peptide:
print(‘AA: ’,aa)

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.

Now, I am going to introduce you to three very interesting functions,


enumerate(), range() and zip(). Though these are not loop-specific
functions, their use along with for loop is ubiquitous.

69
Chapter 9: Conditional Statements

1 >>> #using continue and break in while loop


2 >>> x = 7
3 >>> while x>=0:
4 if x == 2:
5 break
6 x -= 1
7 if x == 4:
8 continue
9 print(x)
10 6
11 5
12 3
13 2
14 >>>
CodeEx 9-9

1 >>> #using continue and break in for loop


2 >>> peptide = ‘QHILK’
3 >>> for aa in peptide:
4 if aa == 'H':
5 continue
6 if aa == 'L':
7 break
8 print(aa)
9
10 Q
11 I
12 >>>
CodeEx 9-10

9.4. enumerate() function


Though enumerate() is not a loop specific function, it is easier to explain with
the context of for loop. enumerate() function takes an iterable object as its
argument and adds a counter to the iterable. It returns an iterable enumerate object (a
python class). Enumerate object stores the items of an iterable and their respective
index as a paired value tuple. It can also be used as a loop iterable that can be
converted into a list of tuples using the list() function on it. See CodeEx 9-11
and CodeEx 9-12.

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

>>> #using enumerate()function with for loop


>>>
>>> gene = [‘GAPDH’,‘p53’,‘actin’,‘SOD2’]
>>> peptide = ‘QHILK’
>>>
>>> #enumerate()list
>>> for index,item in enumerate(gene):
print(‘Index: ’,index,‘, of list item:’,item)

Index: 0 , of list item: GAPDH


Index: 1 , of list item: p53
Index: 2 , of list item: actin
Index: 3 , of list item: SOD2
>>>
>>> #enumerate() string
>>> for i,j in enumerate(peptide):
print(‘Index: ’,i,‘, of str character:’,j)

Index: 0 , of str character: Q


Index: 1 , of str character: H
Index: 2 , of str character: I
Index: 3 , of str character: L
Index: 4 , of str character: K
>>>
CodeEx 9-12

71
Chapter 9: Conditional Statements

9.5. range() function


The range() function returns an integer series within a specified range as an iterable
called range object (another Python class). It is mostly used to generate for loop
iterables. range() is very useful as it helps to automate repetitive works by
supplying iterables as counters for the for loop. range() takes three arguments,
all integers. The first one specifies the starting point of the integer series which is
inclusive and with a default value of 0. The second one specifies the endpoint which is
exclusive and with no default value. So, while using range(), at least you must
specify the endpoint. The last one specifies the increment step, i.e., the differences
between two integers in the series, with a default value 1CodeEx 9-13.

>>> #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.

1 >>> #using range() to create poly-A polymer


2 >>>
3 >>> polya = ‘’ #initiating variable polya with an empty string
4 >>> for i in range(12): #iterating over ranger(12)
5 polya += ‘A’
6
7 >>> print(polya)
8 AAAAAAAAAAAA
9 >>>
CodeEx 9-14

9.6. Improving amino_acid_decoder


Now it’s time to revisit CodeEx 9-4. The amino_acid_decoder asks a user to
input a single letter amino acid code. However, it does that only once. If the user
needs to decode more than one amino acid, she must run the code multiple times. It
is a glitch. The decoder must prompt the user for another input after giving the
output and it will break its operation only when instructed to do so. To achieve the
goal, our code must loop through the block of code until a certain condition is met
(e.g., instruction for termination). Follow CodeEx 9-15 very carefully line-by-line to
understand the debugging protocol.

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

====== RESTART: C:/Users/Desktop/amino_acid_decoder.py ========


Enter single letter amino acid code:g
Glycine(Gly);MW:75.07
CodeEx 9-15

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.

10.1. Opening a file


To work with a file, you must open it first. Python’s built-in open() function does
the job. open() takes two strings as arguments separated by a comma. The first
argument is the file name or its directory, preferably in a raw-string format. The second
argument is the mode of opening. Modes are like permissions about what can be done
with an opened file. Among all modes following three are the most importantCodeEx 10-1:

1. Read-mode: represented by ‘r’. Files opened in read-mode are only allowed to


read. Any kind of modification to the content is prohibited. Read-mode is the
default mode of opening a file. That means if you skip the second positional
argument to open(), a file will open in read-mode by default.
2. Write-mode: represented by ‘w’. Files opened in write-mode are eligible for
modification. Write-mode allows the user to only write data to the file. Just be
Chapter 10: File Handling

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.

>>> #opening file


>>> #file_object = open(“[Link] or file’s path”, ‘mode’)
>>>
>>> #assuming new_file.txt located in the same folder as Python
>>> #then just file name is sufficient as argument
>>> f = open(‘new_file.txt’,‘r’) #open in read-mode or
>>> f1 = open(‘new_file.txt’,‘w’) #open in write mode or
>>> f2 = open(‘new_file.txt’,‘a’) #open in append-mode or
>>> f3 = open(‘new_file.txt’) #open in read-mode by default
>>>
>>> #assuming new_file.txt located in different folder: Desktop
>>> #then file path is mandatory (as raw string)
>>> f = open(r‘C:\Users\Desktop\new_file.txt’,‘r’)
>>> f1 = open(r‘C:\Users\Desktop\new_file.txt’,‘w’)
>>> f2 = open(r‘C:\Users\Desktop\new_file.txt’,‘a’)
>>> f3 = open(r‘C:\Users\Desktop\new_file.txt’)
CodeEx 10-1

10.2. Reading a file


The open() function returns an iterable file object. File object belongs to a special
class _io.TextIOWrapper (line 8-9, CodeEx 10-2) and has its own method like
read(), write(), append(), etc. However, in CodeEx 10-1, variable f, f1
etc. assigned to the file objects returned by open(). File object can be accessed by
more than one strategy.

76
Chapter 10: File Handling

Figure 10-1. new_file.txt showing containing data.

read(), readline(), and readlines() method


File object has read() method for reading the content and it returns the file’s
content as a string objectline 5-7, CodeEx 10-2. I have created ‘new_file.txt’ in
Desktop and it has four linesFigure 10-1. Now I am going to read the file. As Python is
located at a different location, I will use the full path of the text file as the first
argument. See CodeEx 10-3.

1 >>> #reading file


2 >>> #assuming new_file.txt located in the same folder as Python
3 >>>
4 >>> f = open(‘new_file.txt’)
5 >>> content = [Link]()
6 >>> type(content)
7 <class 'str'>
8 >>> type(f)
9 <class '_io.TextIOWrapper'>
10 >>>
CodeEx 10-2

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.

>>> #reading and printing the content of new_file.txt


>>>
>>> f = open(r‘C:\Users\Desktop\new_file.txt’,‘r’)
>>> f_data = [Link]()
>>> print(f_data)
AAAA
TTTT
GGGG
CCCC
>>> [Link]()
>>> #close() method will be discussed later
>>>
CodeEx 10-3

1 >>> #reading by lines: readline() & readlines()


2 >>>
3 >>> f = open(r‘C:\Users\Desktop\new_file.txt’)
4 >>> f_l1 = [Link]()
5 >>> print(f_l1)
6 AAAA
7
8 >>> f_l2 = [Link]()
9 >>> print(f_l2)
10 TTTT
11
12 >>> [Link]()
13 >>>
14 >>> #after closing file must be reopened to read
15 >>>
16 >>> f = open(r‘C:\Users\Desktop\new_file.txt’)
17 >>> f_list = [Link]()
18 >>> print(f_list)
19 [‘AAAA\n’, ‘TTTT\n’, ‘GGGG\n’, ‘CCCC’]
20 >>>
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.

1 >>> #removing ‘\n’ from each line


2 >>>
3 >>> f = open(r‘C:\Users\Desktop\new_file.txt’)
4 >>> f_l1 = [Link]().rstrip(‘\n’)
5 >>> print(f_l1)
6 AAAA
7 >>> f_l2 = [Link]().rstrip(‘\n’)
8 >>> print(f_l2)
9 TTTT
10 >>> f_l3 = [Link]()
11 >>> print(f_l3,end = ‘’)
12 GGGG
13 >>> [Link]()
14 >>>
CodeEx 10-5

Using for loop


A file can be read line-by-line by iterating over the iterable file object using for
loopCodeEx 10-7.

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

>>> #reading file with for loop


>>>
>>> f = open(r‘C:\Users\Desktop\new_file.txt’)
>>> for i in f:
print(i,end = ‘’)

AAAA
TTTT
GGGG
CCCC
>>> [Link]()
>>>
CodeEx 10-6

10.3. Writing a file


write() function is used to write something to a file. But to use it, open the file in
write or append mode. If the file already exists, opening it in write mode wipes out the
old data. However, if the file doesn’t exist, a new one is created. See CodeEx 10-7.

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

>>> #with open(‘file name’,‘mode’) as file_handle:


>>>
>>> with open(r'C:\Users\Desktop\new_file.txt') as f:
print([Link]())

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.

11.1. Defining a function


In Python creating a function is called ‘defining a function’. Here is a small chunk of
code that calculates the number of adenine nucleotides from any polynucleotide
stringCodeEx 11-1. Now suppose for a large program, this A_counter needs to be used
multiple times. So, just converting this piece of code to a function, a_count, will
solve this issue! a_count will return the adenine count of any polynucleotide
string when we call itCodeEx 11-2. Different parts of the function are described in Figure
11-1.
>>> #A_counter
>>> seq = ‘AATGCAT’
>>> a_count = [Link](‘A’)
>>> print(a_count)
3
>>>
CodeEx 11-1

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

Parameter is the place-holder for an


Name of the function (follows the same argument within a function. A function
rule as of variable name assignment). could have more than one comma separated
Function name is arbitrary. parameters
[e.g., def func_name(para,para1…):].
Defining a function Parameter name is also arbitrary and
by keyword def follows the same rule as variables.
Colon is the (:) function
>>> def a_count(parameter): annotation; it’s a must have.
adenine = [Link](‘A’)
return adenine

Instructing the function to return


the run value by keyword return.

Figure 11-1. Different parts of a function

i) Parentheses, after function’s name, enclosing what is called a parameter. A


parameter is a placeholder for an argument. It is like a variable listed inside the
function definition while an argument is a value that is passed to the function
while calling it. Through parameters, a function intakes values, which it
passes to the block of code inside, to work with it.
ii) Though a parameter less function can be written, the function will not take an
argument.
iii) Everything inside a function is inaccessible to the program, as function creates
abstraction and a program can only access a function when you call the
function.
iv) Scope of variable: Variable within a function’s body is called local variable (e.g.,
adenine in CodeEx 11-2, line-4), while a variable outside a function’s
body is called a global variable (e.g., var in CodeEx 11-2, line-10).
Though you know that a variable name is exclusive in a particular program,

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!

1 >>> #‘defining’ a function a_count


2 >>>
3 >>> def a_count(parameter):
4 adenine = [Link](‘A’)
5 return adenine
6 >>>
7 >>> #calling a_count and passing ‘AAAAA’ as an argument and
8 >>> #storing the return value in variable var
9 >>>
10 >>> var = a_count(‘AAAAA’)
11 >>> print(var)
12 5
13 >>>
14 >>> #againg calling it without storing the return value
15 >>>
16 >>> print(a_count(‘AATGAA’))
17 4
18 >>>
CodeEx 11-2

11.2. Positional and keyword arguments


Now I am defining a function, A_checker(), which will check whether a
nucleotide sequence has a particular percentage (%) of adenine contentCodeEx 11-3. The
function will take two arguments, one for the sequence and another for the user-
defined cut-off adenine %. The function will return Boolean values as output. It will

84
Chapter 11: Functions

1 >>> #defining A_checker


2 >>>
3 >>> def A_checker(seq,cutoff):
4 seq_up = [Link]()
5 atgc ={n:seq_up.count(n) for n in seq_up}
6 a_per = (atgc[‘A’]/len(seq_up))*100
7 if a_per > cutoff:
8 return True
9 else:
10 return False
11
12 >>> #calling A_checker() & directly printing it with 1st
13 >>> #positional argument ‘aatgc’ (corresponding to the first
14 >>> #parameter: seq)and 2nd positional argument 20% cut-off
15 >>> #(corresponding to the second parameter: cutoff)
16 >>>
17 >>> print(A_checker(‘aatgc’,20))
18 True
19 >>>
20 >>> #changing 2nd positional argument
21 >>>
22 >>> print(A_checker(‘aatgc’,50))
23 False
24 >>>
25 >>> #messing arguments position will raise error
26 >>>
27 >>> print(A_checker(50, ‘aatgc’))
28 Traceback (most recent call last):
29 File “C:/Users/krish/Desktop/[Link]”, line 27, in <module>
30 print(A_checker(50, ‘aatgc’))
31 File “C:/Users/krish/Desktop/[Link]”, line 4, in A_checker
32 seq_up = [Link]()
33 AttributeError: ‘int’ object has no attribute ‘upper’
34 >>>
35 >>> #continued to CodeEx 11-4
CodeEx 11-3

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,

>>> #keyword arguments (continued from CodeEx 11-3)


>>>
>>> #rewritting the line 27 of CodeEx 11-3 and converting
>>> #positional arguments to keyword arguments by using
>>> #parameters as keywords
>>>
>>> print(A_checker(cutoff = 50, seq = ‘aatgc’))
False
>>>
>>> #note: after tagging keywords to args their positional
>>> #values become insignificant
>>>
CodeEx 11-4

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.

1 >>> #dna concatenator


2 >>> #a function that joins two input DNA strings
3 >>>
4 >>> def dna_concat(seq_1,seq_2):
5 concat_seq = seq_1 + seq_2
6 return concat_seq
7
8 >>> print(dna_concat(‘aaa’,‘ttt’))
9 >>> aaattt
10 >>>
11 >>> #a function exactly takes the number of arguments specified
12 >>> #at the time of defining (i.e., the number of parameters)
13 >>> #e.g., dna_concat() takes exactly two args, alteration to
14 >>> #which elicits an error
15 >>>
16 >>> print(dna_concat(‘aaa’))
17 Traceback (most recent call last):
18 File "C:/Users/krish/Desktop/[Link]", line 16, in <module>
19 print(dna_concat('aaa'))
20 TypeError: dna_concat() missing 1 required positional argument:
21 'seq_2'
22 >>>
23 >>> #another example with 3 args
24 >>>
25 >>> print(dna_concat(‘aaa’,‘ttt’,‘ccc’))
26 Traceback (most recent call last):
27 File “C:/Users/krish/Desktop/[Link]”, line 25, in <module>
28 print(dna_concat(‘aaa’, ‘ttt’, ‘ccc’))
29 TypeError: dna_concat() takes 2 positional arguments but 3 were
30 given
31 >>>
CodeEx 11-5

11.3. Default argument values


Python allows its function’s arguments to have default values. When a programmer
calls a function without an argument, the default values come in handy. In such a

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.

1 >>> #defining a function to check AT content


2 >>>
3 >>> def at_content(input_seq,round_to = 4):
4 seq = input_seq.upper()
5 atgc = {i:[Link](i) for i in seq}
6 at = ((atgc[‘A’]+atgc[‘T’])/len(seq))*100
7 return round(at,round_to)
8
9 >>> #rounding outcome to 2 decimal places
10 >>> print(at_content(‘aatgtcgatcgac’,2))
11 53.85
12 >>>
13 >>> #rounding outcome to 6 decimal places for better accuracy
14 >>> print(at_content(‘aatgtcgatcgac’,6))
15 53.846154
16 >>>
17 >>> #but by default, the function rounds to 4 decimal places
18 >>> print(at_content(‘aatgtcgatcgac’))
19 53.8462
20 >>>
CodeEx 11-6

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.

12.1. Anatomy of module


A module is nothing but a Python script, which contains a set of functions. It’s like a
library of functions; although a module with a single function is also completely
viable. Besides functions, a module can have any other object like a list, string,
dictionary, etc.

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.

12.2. Creating a module


Technically any Python script could act as a module and nothing special about it. So,
creating a module is simple. Just create a Python script with desirable functions and
that is it. Now, I am defining two functions in a new text file and saving it on desktop
as atgc_cal.pyCodeEx 12-1. Now onwards I can use the script as a module.

#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

12.3. Using a module


importing module
As mentioned earlier, the functions of a particular module are not readily available to
use. To use them, you must import the module first by using the import keyword.
In CodeEx 12-2, I am importing atgc_cal.py in a Python script named
[Link]. I am storing [Link] on desktop, the same directory where I
have stored the module.

#importing atgc_cal.py module into the script [Link]

import atgc_cal
CodeEx 12-2

#importing atgc_cal.py module into the script [Link]


import atgc_cal

#now calling at_cal()


at_content = atgc_cal.at_cal(‘aatgcatagatc’,2)
print(at_content)

#calling gc_content()
gc_content = gc_cal(‘aatgcatagatc’,2)
print(gc_content)

=============== RESTART: C:\Users\Desktop\[Link]============


66.67
Traceback (most recent call last):
File "C:\Users\Desktop\[Link]", line 12, in <module>
gc= gc_cal('aatgcatagatc',2)
NameError: name 'gc_cal' is not defined
>>>
>>> #NameError occurred because gc_cal() was called without
reffering to the module. Hence Python could not recognize it.
>>>
CodeEx 12-3

92
Chapter 12: Modules

Calling functions from a module


Now after importing the module, its functions can be accessed using the syntax,
[Link](args). Follow CodeEx 12-3 for better understanding.
Running the program yields the expected result including the error message. Simply
referring to the module while calling its function makes the code error-freeCodeEx 12-4.

#debugging CodeEx 12-3

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)

============== RESTART: C:\Users\Desktop\[Link]=============


66.67
33.3333
>>>
CodeEx 12-4

import function from a module


The syntax of calling a function from a module, [Link](args),
might not be attractive to all. Writing the module name every time could be boring
which is avoidable. Instead of importing the entire module, you can just import a
function of your choice using from keyword to use it independentlyCodeEx 12-5.

#importing the function at_cal() from module atgc_cal.py


from atgc_cal import at_cal

#now calling at_cal()directly w/o module name


at_content = at_cal(‘aatgcatagatc’,2)
print(at_content)

============== RESTART: C:\Users\Desktop\[Link]=============


66.67
>>>
CodeEx 12-5

93
Chapter 12: Modules

Re-naming a Module while importing


For our convenience, Python lets us change the module name while we import it. By
using the as keyword, you can encode the module name at your convenience. For
example, writing atgc_cal every time to call a function is tedious. Instead, create
an alias, a, for the module. Now it would be handy to work withCodeEx 12-6. Creating an
alias does not render any permanent change in the module. This alias is restricted
within the script where you encode it.

#creating an alias when importing the module

import atgc_cal as a

#now just using a instead of atgc_cal

at_content = a.at_cal(‘aatgcatagatc’,2)
print(at_content)

================ RESTART: C:\Users\Desktop\[Link]===========


66.67
>>>
CodeEx 12-6

12.4. Knowing components of a module


After creating a module, it is likely to forget some of its components. This creates
problems while using that module later. Python has an in-built function, dir(),
which gives a list containing all the components of a module. It takes the module
name as its argument CodeEx 12-7.
Here note, dir() returns all properties and methods of the specified object, even
built-in properties which are the default for all object. So, don’t get confused. If you
look closely at the result of CodeEx 12-7, you can distinguish built-in properties
clearly.

94
Chapter 12: Modules

#listing components of atgc_cal.py

import atgc_cal
print(dir(atgc_cal))

['__builtins__', '__cached__', '__doc__', '__file__',


'__loader__', '__name__', '__package__', '__spec__', 'at_cal',
'gc_cal', 'nucleotide']
>>>
CodeEx 12-7

12.5. sys module


Now coming to a practical problem of importing user-defined modules.
Frankly speaking, it’s not possible to synchronize the directories of all user-defined
modules with all the scripts! You are imbibing Python to make your daily task easier
and automated, not boring, and manual! So, make as many modules as you wish and
dump these in any specific folder, at any location, on your PC. Copy the folder path
and forget! Python has its built-in module sys to do the synchronization for you.
Now, start your script anywhere on the PC and access a specific module from any
directory by just three lines of code!

#importing atgc_cal from alien directory to alienmod

import atgc_cal as a
print(dir(a))

============= RESTART: C:\Users\Desktop\[Link]============


Traceback (most recent call last):
File “C:\Users\Desktop\[Link]”, line 3, in <module>
import atgc_cal as a
ModuleNotFoundError: No module named ‘atgc_cal’q
>>>
>>> #Python could not find such a module and thus gives
>>> #ModuleNotFoundError
CodeEx 12-8

95
Chapter 12: Modules

As an example, I have created a folder pyintromodule in the directory:


C:\Users\Documents\pyintromodule and I have moved the
atgc_cal.py module in it. Now I want to import it to a script alienmod in
the directory: C:\Users\Desktop.

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.

1 ‘‘‘adding the module atgc_cal.py’s directory into the check-


2 list of directories which Python check by default using built-
3 in sys module’’’
4
5 import sys
6 if r‘C:\Users\Documents\pyintromodule’ not in [Link]:
7 [Link](r‘C:\Users\Documents\pyintromodule’)
8
9 #now the directory path has been appended to the path list,path
10 import atgc_cal as a
11 print(a.at_cal(‘atgc’,2))

============= RESTART: C:\Users\Desktop\[Link]============


50.0
>>>
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

print(‘The path list is:’,[Link])

#iterating over path and printing its elements individually

for element in [Link]:


print(element)

#now add the module’s path from your PC

if r‘C:\path on your PC’ not in [Link]:


[Link](r‘C:\Users\Documents\pyintromodule’)

CodeEx 12-10

12.6. Python’s built-in modules


Until now, I have mainly talked about how to create a custom module and how to
use it. This would increase your understanding of how Python modules work.
Python has an immense collection of built-in modules and standard libraries for
almost every task you can imagine, and for what you can’t! In real-world Python,
these tools are of extreme importance. You’ve already encountered such a module,
sys. In the next chapter, you will see another such module re, the RegEx module.

97
Chapter 12: Modules

Now, I want to introduce you to another contextually relevant built-in module


random. This is a Pseudo Random Number Generator (PRNG) that generates random
numbers or sequences. In biology, it is useful, especially in simulations. I am here
showing you an interesting use of it. Suppose for some purpose, you need a random
nucleotide or a peptide sequence. Let’s make it withCodeEx 12-11. We are not diving any
further, as this could not be a part of a beginner’s programming text. Also, I am not
explaining it in detail. You are almost at the end of the text. Now, it is your exercise
to understand the code by dissecting it step-by-step. Play with it and use this module
every time you practice generating a random sequence to work with. Your practice
session will be more enjoyable with a brand-new sequence every time!

>>> #generating random DNA seq of specific length


>>> #using choice() method that will randomly choice any
>>> #character from an iterable data type
>>>
>>> import random as r
>>> rand_dna = ‘’.join([Link]('ATGC') for i in range (1000))
>>>
>>> print(len(rand_dna))
>>> print(rand_dna)
>>>
>>> #this can also be written as
>>>
>>> rand_seq = ‘’
>>> for i in range(1000):
rand_seq += [Link](‘ATGC’)

>>> 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.

Patterns are very important in biology. Much of the work we do in computational


biology and bioinformatics is a search for a pattern. It may be a restriction site on a
DNA sequence or a conserved motif in a peptide. It may be a replication origin on
DNA or a poly-A tail of RNA. It might be a search for disease patterns within a
healthy genome or a search for genome-wide patterns between two species to infer
their phylogenies. Programming has given us the momentum we needed for long in
the never-ending quest for these patterns, to fight against severe disease and to
predict their development and fate, to excel in personalized medicine, to know our
ancestry and so on. Such possibilities are ever-expanding with new-age
computational power in our hand!

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

13.2. Finding restriction sites


Restriction site (RES) for EcoRI is straightforward: G/AATTC (/ indicates the
enzyme cut-point). So, finding it in a DNA sequence would not be a big deal.
However, many RESs are elusive. What, if you need to find the RES for the AasI
restriction enzyme, which is GACNNNN/NNGTC ( N could be any of the four
nucleotides A/T/G/C) or RES for AccB1I restriction enzyme, which is G/GYRCC
(Y represents C or T and R represents A or G)? It would be tricky if you try solving
these problems with what you have learned so far, though not impossible. Give it a
try!

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.

#EcoRI RES finder


def ecor1(seq_raw,rs =‘gaattc’):
seq = seq_raw.lower()
loc = [Link](rs)
if loc != -1:
return loc
else:
return ‘not found’

res = ecor1(‘aaattgaattctggca’)
print(‘EcoR1 RES’s location:’,res)

EcoR1 RES’s index: 5


>>>
CodeEx 13-1

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

1 #defining AccB1I RES finding function


2 def accb1(raw_seq,rs=r‘GG(C|T)(A|G)CC’):
3 seq = raw_seq.upper()#upper() or lower() your choice
4 res = [Link](rs,seq)
5 if res:
6 return ‘RES:’+[Link]()+ ‘, at loc:’+str([Link]())
7 else:
8 return ‘not found’
9
10 #now importing the re module and calling accb1()
11 import re
12 res = accb1('aatggcaccggc')
13 print(res)

RES:GGCACC, at loc:3
>>>
CodeEx 13-2

default value of the second parameter: r‘GG(C|T)[AG]CC’. r at the very


beginning makes it a raw string2. Here, characters like |, () are known as
metacharacters. They have special functions. Pipe character (|) in RegEx is equivalent
to ‘either or’. Python interprets C|T and (A|G) as either C or T and either A or G,
respectively. So, Python interprets this RegEx-defined pattern as either GGCACC or
GGCGCC or GGCACC or GGTGCC and searches into the input sequence for a match.

Line-11 is calling re function search(). search() takes two positional


arguments. The first one is the ‘pattern to search for’ and the second one is the ‘sequence
to search in’. It returns a match object (another Python type) if it finds the match.
Otherwise, it returns None. Line-4 stores the search result by assigning it to the res
variable. Note, this res is a local variable as it is specified within the body of the
function (compare line-12 where the res is a global variable). Match-object holds the

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.

Line-6 uses such methods, group() and start() on match-object, res.


group() extracts the content of the match, whereas the start() extracts the starting
position of the match. If no match is found, then the variable res will hold None
and will be evaluated as False in a conditional test and then line-8 will get
executed. The rest of the code is simple and I think it does not require any
explanation here.

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

Table 13-1. RegEx Metacharacters


Metacharacters Search pattern matches Description
A|T A or T Either A or T
GAA|TAA GAA or TAA Either GAA or TAA
(AT) AT Capture and group; treats AT as a group
GA(A|T)AA GAAAA or GATAA Either A or T as they are grouped
A character set. The search pattern
[ATGC] A or T or G or C matches either of the enclosed
characters.
Returns a match for anyone character,
[A-D] A or B or C or D
alphabetically between A and D
A[GC]T AGT or ACT G or C
A (1 or A or X or @ etc. Any single character in place of the dot
A.T
except ‘\n’) T (except newline character)
^AUG AUGTAAA but not AAUGTAA Any string starts with AUG
[^ATGC] NOT (A or T or G or C) Matches anything but not A, T, G, C
GCCGA or GCGGA or
Matches anything but not A, T in
GC[^AT]GA GCXGA or GC#GA or
between GC and GA
GA3GA, etc
TAAAUAA but NOT
UAA$ Any string ends with UAA
AAUGTAUAAA
AT or ATC or ATCC or ATCCC
ATC* Zero or more occurrences of C after AT
or ATCCCC and so on
ATC or ATCC or ATCCC and ATLEAST one or more occurrences of
ATC+
so on, but never AT C after AT
ATC? AT or ATC Zero or ONLY once occurrence of C
ATC{3} Exactly the specified number (3) of
ATCCC
occurrences of C
Exactly the specified number (2) of
(ATC){2} ATCATC
occurrences of ATC(as grouped)
Exactly the specified number (2) of
A(TC){2} ATCTC
occurrences of TC (as grouped)
ATC or ATCC or ATCCC Matches occurrence of C, one or two or
ATC{1,3}
three times
\d Returns a match where the string
contains digits (numbers from 0 to 9)
\
Signals a special character
\D Returns a match where the string
DOES NOT contain any digits

103
Chapter 13: Regular Expression

#defining AccB1I RES finding function


def accb1(raw_seq,rs=r‘GG[CT][AG]CC’):
seq = raw_seq.upper()#upper() or lower() your choice
res = [Link](rs,seq)
if res:
return ‘RES:’+[Link]()+ ‘, at
loc:’+str([Link]())
else:
return ‘not found’

#now importing the re module and calling accb1()


import re
res = accb1(‘aatggcaccggcggcgccta’)
print(res)

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

13.5. Match object and its methods


Match-object holds data about the content and position of the matched pattern.
However, the data are not explicitly available to use as a list or string. Match object
has its methods to extract the data from it.

group(): One such method group(), upon calling on match-object, returns


the portion of the string where it matches the patternCodeEx 13-4.

span(): Another match-object method span() returns a tuple containing the


start-end positions of the matchCodeEx 13-4.

start()& end(): These methods, respectively return the start index and end
index of the matched portion.

104
Chapter 13: Regular Expression

#defining AccB1I RES finding function


def accb1(raw_seq,rs=r‘GG(C|T)[AG]CC’):
seq = raw_seq.upper()#upper() or lower() your choice
res = [Link](rs,seq)
#using dict comprehension
seq_dict = {[Link]():[Link]() for m in res}
return seq_dict

#now importing the re module and calling accb1()


import re
res = accb1(‘aatggcaccggcggcgccta’)
print(res)

{‘GGCACC’: (3, 9), ‘GCGCC’: (12, 18)}


>>>
>>> #matched sequence is the key, its position(tuple containing
start and end) is value in the resulting dictionary seq_dict
>>>
CodeEx 13-4

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

>>> #defining findall()


>>> Import re
>>> result = [Link](r‘gg[ct][ag]cc’,‘aatggcaccggcggcgccta’)
>>> print(result)
>>> ['ggcacc', 'ggcgcc']
>>>
CodeEx 13-5

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).

>>> #demonstrating split()


>>>
>>> import re
>>>
>>> #suppose a raw_dna sequence has impurities
>>>
>>> raw_dna = ‘[Link]’
>>>
>>> #now trimming it to discard impurities and extracting the
>>> #true sequence only
>>> #splitting raw_dna at points where there is no a,t,g,c
>>>
>>> dna_frag = [Link](r‘[^atgc]’,raw_dna)
>>>
>>> #now stitching dna substrings resulted from splitting
>>>
>>> dna = ‘’.join(dna_frag)
>>>
>>> #printing the final cleaned sequence
>>>print([Link]())
ATGCCAAATTAACAGC
>>>
CodeEx 13-6

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).

>>> #demonstrating sub()


>>> import re
>>>
>>> #replacing cgc or ccg with upper UUU
>>>
>>> result = [Link](r'c[gc]g','UUU','aatggcaccggcggcgccta')
>>> print(result)
aatggcaUUUgUUUcgccta
>>>
>>> #though it’s like replace () method discussed earlier
>>> #earlier,here we can replace complex pattern with character
>>> #of our interest
CodeEx 13-7

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

Codon table (x denotes stop codons)


AAA K AGA R CAA Q GAU D CCG P CUG L UAA X UGA X
AAC N AGC S CAC H GCA A CCU P CUU L UAC Y UGC C
AAG K AGG R CAG Q GCC A CGA R GGG G UAG X UGG W
AAU N AGU S CAU H GCG A CGC R GGU G UAU Y UGU C
ACA T AUA I CCA P GCU A CGG R GUA V UCA S UUA L
ACC T AUC I GAA E GGA G CGU R GUC V UCC S UUC F
ACG T AUG M GAC D GGC G CUA L GUG V UCG S UUG L
ACU T AUU I GAG E CCC P CUC L GUU V UCU S UUU F

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.

3 where N could be any of the four nucleotide A/T/G/C


4 where W is A or T , Y is T or C, R is A or G
5 First make the program and then test it with ACS and EACS sequence packed custom sequence

(you have to prepare it) before using it over real sequences.

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.

15.1. Further references


Open Books
1. Think Python: How to Think Like a Computer Scientist (2015) by Allen Downey,
Green Tea Press (2nd Ed); ISBN: 978-1-491-93936-9. An excellent general-
purpose freely available Python Programming text for beginners. The book
could also benefit ‘not so beginners! Perhaps one of the best books you can
start with now.
2. Python for Everybody: Exploring Data Using Python 3 (2016) by
Dr. Charles R. Severance; ISBN: 978-9-352-13627-8. A remixed open book by
Dr. Chuck, based on the title ‘Think Python by Allen Downey’ with an approach
to doing data analysis problems from the very beginning. It is also the
companion text for the great MOOCs course ‘Python for Everybody (University of
Michigan)’.
3. Python for Biologists (2013) by Dr. Martin Jones; ISBN: 978-1-492-34613-5. A
unique, freely available programming book by Dr. Jones written for
Chapter 15: It’s a New Beginning

biologists with many biological problem-oriented micro-projects. I loved this


book and I believe you will love it too.

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

delimiter: A character or string used to indicate where a string should be split.


dictionary comprehension: A compact way to process all or part of the elements in
an iterable and return a dictionary with the results.
dictionary view: The objects returned from [Link](), [Link](),
and [Link]() are called dictionary views. They provide a dynamic view of
the dictionary’s entries, which means that when the dictionary changes, the view
reflects these changes.
dictionary: An associative array, where arbitrary keys are mapped to corresponding
values.
directory: A named collection of files, also called a folder.
docstring: A string that appears at the top of a function definition to document the
function’s interface.
dot notation: The syntax for calling a function in another module by specifying the
module name followed by a dot (period) and the function name.
element: One of the values in a list (or other sequences), also called items.
empty string: A string with no characters and length 0, represented by two
quotation marks.
equivalent: Having the same value.
evaluate: To simplify an expression by performing the operations to yield a single
value.
exception: An error (except syntax error) that is detected while the program is
running.
execute: To run a statement and do what it says.
expression: A piece of syntax that can be evaluated to some value. It is a
combination of variables, operators, and values that represents a single result.
file extension: It’s the suffix which comes after a file name, usually 2 to 4 characters
long. It comes after a period. Examples: .pdf, .mp3, .mkv, .png, .jpeg, .xls, .doc, .py etc.

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

increment: An update that increases the value of a variable (often by one).


index: An integer value used to select an item in a sequence, such as a character in a
string. In Python, indices start from 0.
infinite loop: A loop in which the terminating condition is never satisfied.
initialization: An assignment that gives an initial value to a variable that will be
updated.
instance: An object that belongs to a class.
instantiate: To create a new object.
integer: An immutable type that represents whole numbers.
interactive mode: A way of using the Python interpreter by typing code at the
prompt.
interface: A description of how to use a function, including the name and
descriptions of the arguments and return value.
interpreted language: Python is an interpreted language, as opposed to a compiled
one, though the distinction can be blurry because of the presence of the bytecode
compiler. This means that source files can be run directly without explicitly creating
an executable which is then run. Interpreted languages typically have a shorter
development/debug cycle than compiled ones, though their programs generally also
run more slowly.
interpreter: A program that reads another program and executes it.
invocation: A statement that calls a method.
item: One of the values in a sequence. In a dictionary, another name for a key-value
pair. Also, see the element.
iterable: An object capable of returning its members one at a time. Examples of
iterables include all sequence types (such as list, str, and tuple) and some
non-sequence types like dict, file objects, etc.
iteration: Repeated execution of a set of statements using either a recursive function
call or a loop.

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

parameter: A named entity in a function (or method) definition that specifies an


argument (or in some cases, arguments) that the function can accept, i.e., a name
used inside a function to refer to the value passed as an argument.
path: A string that identifies a file.
PEP: Python Enhancement Proposal. A PEP is a design document providing
information to the Python community, or describing a new feature for Python or its
processes or environment. PEPs should provide a concise technical specification and
a rationale for proposed features. PEPs are intended to be the primary mechanisms
for proposing major new features, collecting community input on an issue, and for
documenting the design decisions that have gone into Python. The PEP author is
responsible for building consensus within the community and documenting
dissenting opinions.
pip: A Python package management tool that comes bundled with Python 3.4 and
above.
polymorphic: Pertaining to a function that can work with more than one type.
portability: A property of a program that can run on more than one kind of
computer.
positional argument: An argument that does not include a parameter name, so it is
not a keyword argument.
print statement: An instruction that causes the Python interpreter to display a value
on the screen.
program: A set of instructions that specifies a computation.
programming: writing instructions/codes for a computer to perform.
prompt: Characters displayed by the interpreter to indicate that it is ready to take
input from the user.
pseudorandom: Pertaining to a sequence of numbers that appears to be random,
but is generated by a deterministic program.

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.

You might also like