Python Lab · Experiment 13
Check a palindrome string using a function
PythonWeek 3JNTUH R22 · CS206ES
Aim
To write a Python function palindrome(s) that returns True if the string s reads the same forwards and backwards and False otherwise, using len to find the length of the string.
Algorithm
- Define the function palindrome(s).
- Set left = 0 and right = len(s) − 1, the positions of the first and last characters.
- While left < right, compare s[left] and s[right]. If they differ, return False.
- Otherwise move left one step right and right one step left.
- If the loop ends without a mismatch, return True.
- In the main program, read a string, call palindrome and print the result.
Program
def palindrome(s):
"""Return True if s reads the same forwards and backwards."""
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
word = input("Enter a string: ")
result = palindrome(word)
print(f"palindrome('{word}') returned {result}")
if result:
print(f"'{word}' is a palindrome")
else:
print(f"'{word}' is not a palindrome")Output
A palindrome
Enter a string: madam
palindrome('madam') returned True
'madam' is a palindromeNot a palindrome
Enter a string: python
palindrome('python') returned False
'python' is not a palindromeEven length palindrome
Enter a string: noon
palindrome('noon') returned True
'noon' is a palindromeRecorded by running this exact program. Typed input appears after each prompt.
How it works
The loop compares characters from both ends and meets in the middle, so it needs only about half as many comparisons as the length. For an odd-length string the middle character is never compared, which is fine because it matches itself.
An empty string and a one-character string are palindromes: the loop does not run and the function returns True.
The check is case-sensitive, so "Madam" is not a palindrome here. Call palindrome(word.lower()) to ignore case.
A shorter way is s == s[::-1], where s[::-1] is the string reversed. The loop is used here because the exercise asks you to work with len.
Common mistakes
Setting
right = len(s). The last index islen(s) - 1;s[len(s)]raisesIndexError.Returning True as soon as one pair matches. You can only return True after every pair has been checked, so
return Truegoes after the loop.Printing inside the function instead of returning True or False. The task asks for a function that returns a Boolean.
Forgetting that the comparison is case-sensitive. Convert the string with
lower()first if case should not matter.
Viva questions
Try to answer each one aloud before you open it.
What is a palindrome?
A word, number or sentence that reads the same forwards and backwards, such as madam, noon or 12321.
What does len return for a string?
The number of characters in it.
len("madam")is 5.What are the first and last valid indexes of a string s?
0 and
len(s) - 1. Python also allowss[-1]for the last character.How else can you reverse a string in Python?
With the slice
s[::-1], or with"".join(reversed(s)).Is the empty string a palindrome?
Yes. It reads the same both ways, and the function returns True for it.