NameError: name [name] is not defined

1

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

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 does this error occur, and how do I 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
    
asked by anonymous 05.10.2016 / 00:31

1 answer

3

You have some problems with your code, but this is not the focus of the question.

This error is because of these lines

C = C + 1
G = G + 1

Since C and G were not declared, you can not assign them the value of themselves incremented by 1. Simply declaring the 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)
    
05.10.2016 / 01:44