Example solutions for script 04_looping exercise block 3

Exercise 3.2

seq = "GCCGGA"
for i in range(len(seq)):
    if seq[i] == "G":
        print("found G at position", i)
found G at position 0
found G at position 3
found G at position 4

Exercise 3.3

text = input("give me some text: ")

a_count = 0
for i in range(len(text)):
    if text[i] == "A":
        a_count += 1
        
print("found A", a_count, "times in your input")
give me some text: Abracadabra AllabamAH
found A 3 times in your input

Exercise 3.4

We use the round function to prettify the output. Again count_g += 1 is the same as count_g = count_g + 1:

seq = "GCCGGA"
count_g = 0
count_c = 0
for i in range(len(seq)):
    if seq[i] == "G":
        count_g += 1
    elif seq[i] == "C":
        count_c += 1
        
rel_gc_content = (count_g + count_c) / len(seq) * 100.0

print("relative gc countent is", round(rel_gc_content, 2), "%")
relative gc countent is 83.33 %

Exercise 3.5

text = "racecar"

reverted = ""

for i in range(len(text)):
    reverted = text[i] + reverted
    
print(text, "reverted is", reverted)
racecar reverted is racecar