HomeAboutSoftwarePublicationsPostsMicroBinfie Podcast

Lessons learnt about programming - exercise one

Posted on August 24, 2023
an AI generated picture (Midjourney) with prompt; 'computer programming in the style of David by Michelangelo'. You can share and adapt this image following a CC BY-SA 4.0 licence.

This post is part of a series that summarised a workshop we ran recently. We were discussing programming, discussing common pitfalls, and then looked at some fun python tricks.

There are several sections:

What is wrong with this code?

Here is a simple error that you might encounter when programming. It's a simple error, but it's easy to make, and it's easy to miss. It's also easy to fix, once you know what to look for. What issues you can see?

N.B. download_from_ncbi_long() takes about 2 seconds, each time it's run.

python
from time import sleep
def download_from_ncbi_long():
sleep(2)
return ["gyrA", "katG", "dnaA"]
def gene_search(data):
for item in data:
for gene_name in item:
reference_list = download_from_ncbi_long()
if gene_name in reference_list:
print(f'Gene found {gene_name}')
my_genes = [["lacZ", "rpoB", "recA"], ["gyrA", "katG", "dnaA", "ftsZ", "ompF", "rpoD", "fabH"]]
gene_search(my_genes)

The output:

python
Gene found gyrA
Gene found katG
Gene found dnaA

How can we improve?

download_from_ncbi_long() takes about 2 seconds, each time it's run.

python
def gene_search(data):
reference_list = download_from_ncbi_long() # Move this outside the loop
for item in data:
for gene_name in item:
if gene_name in reference_list:
print(f'Gene found {gene_name}')

Questions or comments? @ me on Mastodon @happykhan@mstdn.science or Twitter @happy_khan

The banner image is an AI generated picture (Midjourney) with prompt; 'computer programming in the style of David by Michelangelo'. You can share and adapt this image following a CC BY-SA 4.0 licence.