The function failed to return a value. In the end it should have a return final
:
def dnaComplement(s):
complement = []
complement0 = reversed(s)
for character in complement0:
if character == 'G':
complement.append('C')
elif character == 'C':
complement.append('G')
elif character == 'A':
complement.append('T')
elif character == 'T':
complement.append('A')
final = ''.join(complement)
print(final)
return final # <-- aqui
When there’s no return
, the function returns None
¹ (see more details on documentation). Placing a return value, it behaves as you expect, returning the string.
Or even, if you don’t want to print and you don’t want to use the variable final
for nothing else, nor need it, can directly return the result of join
:
def dnaComplement(s):
complement = []
complement0 = reversed(s)
for character in complement0:
if character == 'G':
complement.append('C')
elif character == 'C':
complement.append('G')
elif character == 'A':
complement.append('T')
elif character == 'T':
complement.append('A')
return ''.join(complement)
And as the return of join
is already a string, no need to use str(dnaComplement(s))
, just call the function directly you will already have a string:
s = input()
result = dnaComplement(s) # retorno da função é uma string, não precisa de str()
# etc...
Not directly related, but you can simplify the function using a dictionary containing the mappings between characters:
def dnaComplement(s):
comps = { 'G': 'C', 'C': 'G', 'A': 'T', 'T': 'A' }
complement = []
for character in reversed(s):
complement.append(comps[character])
return ''.join(complement)
And you can still use one Generator Expression (much more succinct and pythonic), there is no need to generate the list complement
:
def dnaComplement(s):
comps = { 'G': 'C', 'C': 'G', 'A': 'T', 'T': 'A' }
return ''.join(comps[character] for character in reversed(s))
1: the exception to this rule is when the function has a yield
instead of return
, then she becomes a Generator.