Nameerror: name [name] is not defined

Asked

Viewed 13,034 times

4

I need to do Python programming to know the CG percentage in a DNA string...

maior = 0
dnaMaior = ""
while True:
     dna = input("Digite uma sequencia de DNA: ")
     if dna == "Z" or dna == "z":
      break
     else:
        tam = len(dna)
        indice = 0
        while indice < len(dna):
            if dna == "C" or dna == "G":
                C = C + 1
                G = G + 1
            indice = indice+1
        percCG = ((C+G)*100)/len(dna)
        maior = percCG
        dnaMaior = dna
        print(dnaMaior)

There is a syntax error. Why this error occurs, and how to fix it?

Digite uma sequencia de DNA: CCCCCCCGGGGGGGGAAAAAAAATTTT
Traceback (most recent call last):
  File "C:/Users/13104855/Downloads/exerc_02T2.py", line 18, in <module>
    percCG = ((C+G)*100)/len(dna)
NameError: name 'C' is not defined

1 answer

6

There are some problems in your code, but this is not the focus of the question.

This error is because of those lines

C = C + 1
G = G + 1

Since C and G are not declared, you cannot assign them the value of themselves incremented by 1. Simply declaring variables before entering the loop already solves

maior = 0
dnaMaior = ""
while True:
     dna = raw_input("Digite uma sequencia de DNA: ")
     if dna == "Z" or dna == "z":
      break
     else:
        tam = len(dna)
        indice = 0
        C = 0
        G = 0
        while indice < len(dna):
            if dna == "C" or dna == "G":
                C = C + 1
                G = G + 1
            indice = indice+1
        percCG = ((C+G)*100)/len(dna)
        maior = percCG
        dnaMaior = dna
        print(dnaMaior)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.