Reputation: 93
I am new to programming and I am trying to write a code about DNA, where a user enters a specific DNA sequence. the program must then translate the DNA entered into a specific amino acid.
I have tried to convert each DNA string entered by the user into a list, and then using the "in" function to see which DNA entered by the user corresponds with the specific amino acid. my code is below:
dna = input("please enter the DNA sequence in CAPS: ")
# a variable called codons to convert the entered DNA sequence into a list of 3 characters per element
codons = [dna[start:start+3] for start in range (0,len(dna),3)]
# we now create an if structure which matches each codon to its appropriate amino acid
if "ATA" or "ATC" or "ATT" in codons:
print("Isoleucine")
if "CTT" or "CTC" or "CTA" or "CTG" or "TTA" or "TTG" in codons:
print("Leucine")
if "GTT" or "GTC" or "GTA" or "GTG" in codons:
print("Valine")
if "TTT" or "TTC" in codons:
print("Phenylalanine")
if "ATG" in codons:
print("Methionine")
the problem is when I run the code, it is printing most of the codon types instead of specific amino acids e.g. if the user enters "ATA", it prints Isoleucine, Leucine, Valine and Phenylalanine instead of only printing Isoleucine.
Upvotes: 1
Views: 140
Reputation: 1
'in' operator has higher predecence than 'or'. Therefore, your expressions are equivalent to
if "ATA" or "ATC" or "ATT" in codons:
==>
if "ATA" or "ATC" or ("ATT" in codons):
which evaluates to "ATA".
Either use (x in y) or (z in y) ... or define a function like
def any_in(elements, container):
for element in elements:
if element in container:
return True
return False
and call it:
if any_in(["ATA", "ATC", "ATT"], codons):
...
https://www.programiz.com/python-programming/precedence-associativity
Upvotes: 0
Reputation: 11073
Try something like this:
if any(i in codons for i in ["ATA" , "ATC", "ATT"]):
# your prints
instead of writing two much ors.
Upvotes: 4