Function Fundamentals problem8 not getting the correct result

Screen Link:
Python Fundamentals Practice Problems | Dataquest

My Code:
def is_palindrome(dna):
n = len(dna)
for i in range(n//2):
if dna[i] == dna[n-i-1]:
return True
return False


Replace this line with your code

What I expected to happen: False

What actually happened: True

Replace this line with the output/error

Hi @aashaydabli96:

Kindly and format your code as per these guidelines and indent the lines accordingly so we can help to better troubleshoot! Thanks

Hi @aashaydabli96 and welcome to the community!

The reason your code is not giving you the desired result is because of this bit of code:

if dna[i] == dna[n-i-1]:
    return True

which says “If the first character is the same as the last character then return True.” The problem with this approach is that it will return True after testing just the first/last character combination and will not continue to check the other characters because a return statement will terminate the loop. To fix this, try “taking the negative approach” so that if the characters don’t match, return False.

1 Like

Thank you, that was very helpful. I realized that the loop will terminate just at the first iteration as the indented code of the if statement gets executed.

1 Like