Conditionals


Conditionals are used to tell your computer to do a set of instructions depending on whether or not a Boolean is True. In other words, we are telling the computer:

if something is true:
    do task a
otherwise:
    do task b

In fact, the syntax in Python is almost exactly the same. As an example, let’s ask whether or not a codon is the canonical start codon (AUG).

[2]:
codon = 'AUG'

if codon == 'AUG':
    print('This codon is the start codon.')
This codon is the start codon.

The syntax of the if statement is apparent in the above example. The Boolean expression, codon == 'AUG', is called the condition. If it is True, the indented statement below it is executed. This brings up a very important aspect of Python syntax.

Indentation matters.

Any lines with the same level of indentation will be evaluated together.

[3]:
codon = 'AUG'

if codon == 'AUG':
    print('This codon is the start codon.')
    print('Same level of intentation, so still printed!')
This codon is the start codon.
Same level of intentation, so still printed!

What happens if our codon is not the start codon?

[4]:
codon = 'AGG'

if codon == 'AUG':
    print('This codon is the start codon.')

Nothing is printed. This is because we did not tell Python what to do if the Boolean expression codon == 'AUG' evaluated False. We can add that with an else clause in the conditional.

[5]:
codon = 'AGG'

if codon == 'AUG':
    print('This codon is the start codon.')
else:
    print('This codon is not the start codon.')
This codon is not the start codon.

Great! Now, we have a construction that can choose which action to take depending on a value. So, if we’re zooming along an RNA sequence, we could pick out the start codon and infer where translation would start. Now, what if we want to know if we hit a canonical stop codon (UAA, UAG, or UGA)? We can nest the conditionals!

[6]:
codon = 'UAG'

if codon == 'AUG':
    print('This codon is the start codon.')
else:
    if codon == 'UAA' or codon == 'UAG' or codon == 'UGA':
        print('This codon is a stop codon.')
    else:
        print('This codon is neither a start nor stop codon.')
This codon is a stop codon.

Notice that the indentation defines which clause the statement belongs to. E.g., the second if statement is executed as part of the first else clause.

We can be more concise and avoid the nesting by using an elif clause.

[7]:
codon = 'UGG'

if codon == 'AUG':
    print('This codon is the start codon.')
elif codon == 'UAA' or codon == 'UAG' or codon == 'UGA':
    print('This codon is a stop codon.')
else:
    print('This codon is neither a start nor stop codon.')
This codon is neither a start nor stop codon.

Computing environment

[8]:
%load_ext watermark
%watermark -v -p jupyterlab
Python implementation: CPython
Python version       : 3.8.11
IPython version      : 7.26.0

jupyterlab: 3.1.7