7.6. Nested conditions

However, construction with multiple alternatives are sometimes not sufficient and you need to nest condition like this:

>>> primerLen = len(primer)
>>> primerGC  = float(count(primer, 'g') + count(primer, 'c'))/ primerLen

>>> if primerGC > 50:
...    if primerLen > 20:
...       PCRprogram = 1
...    else:
...       PCRprogram = 2
... else:
...    PCRprogram = 3      
      

Exercise 7.2. Nested condition

Why is it impossible to write the above example as chained condition?

Figure 7.6 shows the scheme of nested conditions.

Figure 7.6. Nested conditions

Sometimes you can simplify nested conditions by constructing more complex conditions with boolean operators.

>>> primerLen = len(primer)
>>> primerGC  = float(count(primer, 'g') + count(primer, 'c'))/ primerLen

>>> if primerGC > 50:
...    if primerLen > 20:
...       PCRprogram = 1
... else:
...    PCRprogram = 2      
      
can be expressed as:
>>> if primerGC > 50 and primerLen > 20:
...    PCRprogram = 1
... else:
...    PCRprogram = 2      
      

Caution

Even if the second version is easier to read, be careful and always check whether the complex condition you have written, is what you really want. Such errors are called semantic error. They can not be detected by the interpreter because the syntax of the program is correct, even if it is not necessarily what you want to compute.