In Python, you can specify more than one alternative:
>>> seq = 'vATGCAnATG'
>>> base = seq[0]
>>> base
v
>>> if base in 'ATGC':
... print "exact nucleotid"
... elif base in 'bdhkmnrsuvwxy':
... print "ambiguous nucleotid"
... else:
... print "not a nucleotid"
...
ambiguous nucleotid
The elif statement is used to give an
alternative condition. What happens when this is executed? The
conditions are evaluated from top to bottom. In our example with
base = 'v' as first condition, the
if condition base in
'ATGC' is false, so the next condition, that of the
elif statement is evaluated. base
in 'bdhkmnrsuvwxy' is true, so the block of statements
of this clause is executed and ambiguous
nucleotid is printed. Then the evaluation of the
condition is stopped and the flow of execution continues with
the statement following the if-elif-else
construction.
![]() | Multiple alternative conditions |
|
Multiple alternative conditions are conditions that are tested from top to bottom. The clause of statements for the first alternative that is evaluated as true is executed. So there is exactly one alternative that is executed, even if there are more than one that are true. In this case the clause of the first true condition encountered is chosen. Figure 7.5 illustrates this. | |
The else statement is optional. But it is more safe to catch the case where all of the given conditions are false.
![]() | Exercise 7.1. Chained conditions |
|
The elif statement only facilitates the writing and legibility of multiple alternative conditions. How would you write a multiple condition without this statement (Solution 7.1)? Hint: See the scheme of Figure 7.5. | |