Loops in Python: While loop

Many a times we will encounter a a situation where we have iterate over a group of statements until a specific condition is met. The number iterations that the loop should run is not fixed or known. In such cases, while loop is use. 

Statements inside a while loop iterate until a given condition is true. Following is a simple example. 




 

Here we begin a number with 1. We also create an empty dictionary to store the key-value pair of the numbers and their squares. We run the loop until the square of the number is less than 1000. Following is the code:

n = 1
n_sq = {}
while n**2 < 1000:
    n_sq[n] = n**2 # make a dictionary of the numbers and their squares
    n += 1
    
print(n_sq)

In real situation, you might be reading through several lines of data which you have to parse. Typically, you would want to read through lines until you find some marker in your data which indicates you to do something else. While loop comes in use here to keep on reading through or keep on executing some lines until a specific marker is found in data.

One example is parsing of fasta files of sequence data as shown below. The ">" sign in fasta file is a marker of start of a new sequence and the name of the sequence. Each fasta file can contain several sequences whose sequence name begin with the marker ">" and actual sequence begins from next line. In a given fasta file, due to the differences in the length of the sequences, each sequence occupies different number of lines. So, we really don't know when a sequence will finish reading. Therefore, one way of doing it is to read the sequence until we encounter the ">" sign which is the marker that next sequence has started.


 

 

Popular posts from this blog

Principal Coordinate analysis in R and python

Principal Coordinate Analysis (PCoA) in R