Your for
loop checks all pairs of characters, no matter if it found mismatch or not. So, in case of string '38113' it will return True
, because the flag
variable will be set to True
after the check for equality of last digit in '38113' and its reversed version '31183' (both equal to 3, while the string isn't a palindrome).
So, you need to return False
right after you've found mismatch; if you checked all the characters and didn't find it - then return True
, like so:
def palindrome(num):
r = num[::-1]
for i in range (0, len(num)-1):
if(r[i] != num[i]):
return False
return True
Also, as someone pointed out it'll be better to use python's slices - check out the documentation.