Search code examples
pythonloopsbioinformaticsindex-error

Problem with my Python code: IndexError: string index out of range


Recently I was working on a python challenge where I needed to create a function that was capable of transcribing DNA to mRNA, but every time I run the code I receive the same error message:

if dna[y] == "A": IndexError: string index out of range

Can anyone help me? Below is a sample of my code.

global y
y = 0
global rna
rna = ""
def dna_to_rna(dna):
    global y
    global rna
    for i in range(len(dna)):
        if dna[y] == "A":
            rna += "U"
        elif dna[y] == "T":
            rna += "A"
        elif dna[y] == "G":
            rna += "C"
        else:
            rna += "G"
        y += 1
    return rna  

Solution

  • You have a lot of extra variables and you don't need 'global' modifiers in your code. I've done some reformatting to your code, try this:

    def dna_to_rna(dna: str) -> str:
      rna = ""
      for i in range(len(dna)):
          if dna[i] == "A":
              rna += "U"
          elif dna[i] == "T":
              rna += "A"
          elif dna[i] == "G":
              rna += "C"
          elif dna[i] == "C":
              rna += "G"
          else:
              return "Invalid Sequence!"
      return rna