Lesson 6 of 14 · 11 min
Making Decisions with Conditionals
Programs often need to react differently depending on the data they are given. A conditional is a piece of code that checks whether something is true and then decides what to do next. In this lesson you will use conditionals to classify DNA bases and to inspect short sequences.
Comparison operators
A comparison operator asks a yes-or-no question and answers with a Boolean value, which is a value that is either True or False. The operator == checks whether two values are equal, != checks whether they are not equal, and > checks whether the left value is greater than the right. An if statement runs its indented block only when the question is True.
base = "A" # store one single-letter DNA base in a variable named base
print(base == "A") # == checks if two values are equal, so this prints True
print(base != "G") # != checks if two values are NOT equal, so this prints True
# The if statement runs the indented line below only when its question is True.
if base == "A":
print("This base is adenine")True
True
This base is adenine
if, elif, else
base = "G" # try changing this to "C", "T", or "X" and running it again
# Purines are the larger bases: adenine (A) and guanine (G).
# Pyrimidines are the smaller bases: cytosine (C) and thymine (T).
# The word or gives True when at least one side of it is True.
if base == "A" or base == "G":
print("Purine")
# elif means "else if"; it is checked only when the if above was False.
elif base == "C" or base == "T":
print("Pyrimidine")
# else runs when none of the conditions above were True.
else:
print("Not a standard DNA base")Purine
Boolean logic
seq = "ATGCGT" # a short DNA sequence written as a string of letters
base = "N" # a single base we want to validate
# seq[0:3] takes the first three letters of seq (positions 0, 1, and 2).
# len(seq) counts the letters in seq, and > checks "greater than".
# The word and gives True only when BOTH sides of it are True.
if seq[0:3] == "ATG" and len(seq) > 3:
print("Start codon ATG found, with more bases after it")
# is_valid is True when base matches any one of the four standard DNA letters.
is_valid = base == "A" or base == "C" or base == "G" or base == "T"
# The word not flips True into False and False into True.
if not is_valid:
print("Invalid character detected:", base)Start codon ATG found, with more bases after it
Invalid character detected: N
Try it yourself: Change base in the last example to "C" and predict what prints before you run it. Then write an if / elif / else block that reads a three-letter codon and prints "Stop codon" when the codon equals "TAA", "TAG", or "TGA", and prints "Not a stop codon" for anything else.