Conditions and loops
An if statement chooses what to do. A for loop repeats an action for each item.
dna = "ATGCGC"
gc_count = 0
for base in dna:
if base == "G" or base == "C":
gc_count = gc_count + 1
print(gc_count)Count each base
counts = {"A": 0, "C": 0, "G": 0, "T": 0}
for base in dna:
if base in counts:
counts[base] = counts[base] + 1
print(counts)A dictionary stores pairs such as base → count. The in check prevents an unsupported letter from being counted as one of the four canonical bases. Real input also needs validation and a clear policy for ambiguity codes.
Exercises
- Change the DNA to
"GGATCC". What should the GC count be? - Add an
elsebranch that prints an “unexpected symbol” message for a character outside A/C/G/T.
Worked answer
The GC count is 4 (two G and two C). In the loop, use else: print("Unexpected symbol", base) after the membership test. In larger programs, raising a clear error is often safer than only printing.