ubuntu2004
Loops III - controlling and nesting loops
Breaking out of a loop: break
In Exercise 12.3 we looped through all DNA sequences in the list DNA_sequences
testing if they contained the start codon "ATG".
Say, for example, we want to loop through the list until we find the first DNA sequence containing a start codon and then we stop looping. We can do this by breaking out of the loop early, i.e., before we reach the end of the list.
As we loop through the list of DNA sequences we test if the start codon "ATG" is in the current sequence. If it isn't we do nothing a move on to the next sequence in the list. However, if "ATG" is in the current sequence we assign the sequence to the variable found
(which was previously empty) and immediately break out of the loop without testing the remaining sequences.
If no sequence in the list contains "ATG" then we will loop through all sequences in the list and the variable found
will still be empty after we exit the loop normally.
Next we do something we haven't seen before. We test if found
is non-empty, which means it contains a DNA sequence. If it is non-empty then the condition
is True and we print the sequence with "ATG" in it. However, if found
is still empty then the condition if found:
is False and therefore we print that no DNA sequence with ATG in it was found.
If you remove the "ATG" in the second sequence in the list DNA_sequences
and rerun the code you will see that no sequence with a start codon is found.
Nested loops
Loops can be nested, i.e., one loop inside another.
In the following code we count the number of occurrences of each base in each DNA sequence in a list.
In the top loop we loop through each DNA sequence: dna_seq
is the iterating variable.
We then loop through the four bases A, C, G and T in turn. base
is the iterating variable. Note that this loop is indented, which means it is inside the previous loop. This loop is repeated once for each DNA sequence.
We use the string method count()
to count the number of occurrences of base
in dna_seq
and print out the result.
We use a conditional statement to test if there is just one occurrence so that the output is grammatically correct.