pythonforbio.
[WASM idle]
Python Basics06/12

Loops

Starting sandbox…
Beginnerpuzzle3 tests

A for loop repeats a block once per item.

genes = ["TP53", "BRCA1", "EGFR"]

for gene in genes:
    print(gene)

range

range(stop) counts from 0. range(start, stop, step) gives full control. The stop value is excluded.

for index in range(3):
    print(index)

for position in range(0, 9, 3):
    print(position)

Stepping by 3 is how you walk a sequence codon by codon.

sequence = "ATGGCCATT"
for start in range(0, len(sequence), 3):
    print(sequence[start:start + 3])

enumerate and zip

enumerate gives the index alongside the item. zip walks two sequences together.

genes = ["TP53", "BRCA1"]
depths = [120, 88]

for index, gene in enumerate(genes, start=1):
    print(index, gene)

for gene, depth in zip(genes, depths):
    print(gene, depth)

break and continue

break leaves the loop. continue skips to the next item.

for depth in [30, 12, 45, 7]:
    if depth < 20:
        continue
    print(depth)

for depth in [30, 12, 45]:
    if depth > 40:
        print("found", depth)
        break

while

while repeats until its condition becomes false. Use it when the number of repetitions is not known in advance.

remaining = 5
while remaining > 0:
    remaining -= 2
print(remaining)

Task

Write codons(sequence). Split sequence into 3-character codons and return them as a list. Ignore any trailing 1 or 2 characters that do not form a complete codon.

Test cases · 3

#viainputexpected stdout
1stdinATGGCCATT['ATG', 'GCC', 'ATT']
2stdinATGGCCAT['ATG', 'GCC']
3stdinAT[]

Hints · 2

01Hint

range(0, len(sequence), 3) gives each codon start position.

02Hint

A slice past the end is short, so check its length before keeping it.

starter

No output yet — run the code to populate this drawer.

ConditionalsFunctions