Why wouldn't this palindrome test work?
python
Solution
The way the body of the loop is coded the values of `pal` may change between `True` and `False` repeatedly depending on whether a given pair of characters happen to match or not during that particular iteration.
Better to check for inequality, set your Boolean variable `pal` to `False` and drop out of the loop immediately then.
Something like this:
def palindrome2(s):
n = len(s)
pal = True
for i in range(n/2)
if s[i] != s[n-i-1]: # the moment it's false
pal = False # set pal and
break # drop out of the loop
return pal
alternatively, without using a Boolean variable:
...
for i in range(n/2)
if s[i] != s[n-i-1]: # the moment it's false
return False # exit the function by returning False
return True # otherwise return True
Problem
A palindrome is a string that reads the same forwards and backwards. Examples of palindromes include "lol", "abba", "radar", and "pickle elkcip". Indicate whether or not it works under all circumstances described in the following docstring: '''Return True if string s is a palindrome and return False otherwise.''' ``` def palindrome2(s): n = len(s) pal = True for i in range(n/2): if s[i] == s[n-i-1]: pal = True else: pal = False return pal ``` I don't get why this function wouldn't work. To me, it seems as if the function works. Apparently, the booleans are misused but I don't get how the booleans above are not used properly. Can someone please explain this to me?