While loop

Many a times we will encounter a situation where we have to 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 used.

Statements inside a while loop are executed iteratively until a given condition is True. Following is a simple example.

Python





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

In this small program, the number n starts with the value 1.
In the while loop, square of n is calculated. The number n is then added as a key to the dictionary n_sq with its value equal to its square.
In the end the value of n is increased by one.
The loop is terminated when a n reaches a value such that its sqaure is greater than 1000.

The value of the variable which is used in the condition to enter the while loop needs to change inside the while loop, otherwise we will get something called as an ‘infinite loop’.

In real situations, 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 containing multiple sequences. The individual sequances vary in their lengths and take up different number of lines in the fasta file. One sequance may be over within 10 lines and other might span more than 100 lines.

The “>” sign in fasta file is a marker of start of a new sequence and also contains the name of the sequence. The actual sequence begins from next line. While parsing such files we really don’t know how many lines to read until we encounter new sequence. 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.