DNA Visualization

Tags: short, artistic, science, scrolling

Deoxyribonucleic acid is a tiny molecule that exists in every cell of our bodies and contains the blueprint for how our bodies grow. It looks like a double helix (a sort of twisted ladder) of pairs of nucleotide molecules: guanine, cytosine, adenine, and thymine. These are represented by the letters G, C, A, and T. DNA is a long molecule; it’s microscopic, but if it were stretched out, its 3 billion base pairs would be 2 meters long! This program is a simple animation of DNA.

dna_visualization.py
 1"""DNA, by Al Sweigart al@inventwithpython.com
 2A simple animation of a DNA double-helix. Press Ctrl-C to stop.
 3Inspired by matoken https://asciinema.org/a/155441
 4This code is available at https://nostarch.com/big-book-small-python-programming
 5Tags: short, artistic, scrolling, science"""
 6
 7import random, sys, time
 8
 9PAUSE = 0.15  # (!) Try changing this to 0.5 or 0.0.
10
11# These are the individual rows of the DNA animation:
12ROWS = [
13    #123456789 <- Use this to measure the number of spaces:
14    '         ##',  # Index 0 has no {}.
15    '        #{}-{}#',
16    '       #{}---{}#',
17    '      #{}-----{}#',
18    '     #{}------{}#',
19    '    #{}------{}#',
20    '    #{}-----{}#',
21    '     #{}---{}#',
22    '     #{}-{}#',
23    '      ##',  # Index 9 has no {}.
24    '     #{}-{}#',
25    '     #{}---{}#',
26    '    #{}-----{}#',
27    '    #{}------{}#',
28    '     #{}------{}#',
29    '      #{}-----{}#',
30    '       #{}---{}#',
31    '        #{}-{}#']
32    #123456789 <- Use this to measure the number of spaces:
33
34try:
35    print('DNA Animation, by Al Sweigart al@inventwithpython.com')
36    print('Press Ctrl-C to quit...')
37    time.sleep(2)
38    rowIndex = 0
39
40    while True:  # Main program loop.
41        # Increment rowIndex to draw next row:
42        rowIndex = rowIndex + 1
43        if rowIndex == len(ROWS):
44            rowIndex = 0
45
46        # Row indexes 0 and 9 don't have nucleotides:
47        if rowIndex == 0 or rowIndex == 9:
48            print(ROWS[rowIndex])
49            continue
50
51        # Select random nucleotide pairs, guanine-cytosine and
52        # adenine-thymine:
53        randomSelection = random.randint(1, 4)
54        if randomSelection == 1:
55            leftNucleotide, rightNucleotide = 'A', 'T'
56        elif randomSelection == 2:
57            leftNucleotide, rightNucleotide = 'T', 'A'
58        elif randomSelection == 3:
59            leftNucleotide, rightNucleotide = 'C', 'G'
60        elif randomSelection == 4:
61            leftNucleotide, rightNucleotide = 'G', 'C'
62
63        # Print the row.
64        print(ROWS[rowIndex].format(leftNucleotide, rightNucleotide))
65        time.sleep(PAUSE)  # Add a slight pause.
66except KeyboardInterrupt:
67    sys.exit()  # When Ctrl-C is pressed, end the program.

https://inventwithpython.com/bigbookpython/project21.html