Skip to content
Laviyx Learn

Try

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

  1. Define the function palindrome(s).
  2. Set left = 0 and right = len(s) − 1, the positions of the first and last characters.
  3. While left < right, compare s[left] and s[right]. If they differ, return False.
  4. Otherwise move left one step right and right one step left.
  5. If the loop ends without a mismatch, return True.
  6. In the main program, read a string, call palindrome and print the result.

Program

Python
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

Output 1
Enter a string: madam
palindrome('madam') returned True
'madam' is a palindrome

Not a palindrome

Output 2
Enter a string: python
palindrome('python') returned False
'python' is not a palindrome

Even length palindrome

Output 3
Enter a string: noon
palindrome('noon') returned True
'noon' is a palindrome

Recorded 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 is len(s) - 1; s[len(s)] raises IndexError.

  • Returning True as soon as one pair matches. You can only return True after every pair has been checked, so return True goes 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 allows s[-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.

Learn the concepts

All Python Programming Lab experiments →