Palindrome Checker with Python

Oliver Lövström
Internet of Technology
5 min readJan 29, 2024

In this article, we will create a Python program that checks if a phrase is a palindrome. A palindrome is a phrase that reads the same forwards and backward, such as “racecar” and “level”.

Photo by Surendran MP on Unsplash

This project is an excellent starting point for beginners to understand the basics of Python. Don’t worry if you are new to programming; we’ll walk you through each step together. And if you’re eager to see the full code right away, you can find it at the end of the article or on GitHub.

Palindrome Checker

We’ll start by defining a function called is_palindrome. This function takes a string (a sequence of characters) and returns a Boolean value (True or False), indicating whether or not the string is a palindrome.

def is_palindrome(phrase: str) -> bool:
"""Check if phrase is a palindrome.

:param phrase: The phrase to check if it is a palindrome."
:return: `True` if the phrase is a palindrome.
"""
return phrase == phrase[::-1]

Let’s break it down:

  1. def is_palindrome(phrase: str) -> bool: Here, we define a function named is_palindrome, it has one parameter phrase, which is expected to be a string (str) . The -> bool indicates that our function will return a boolean value.
  2. Docstring: Inside the triple quotes is a docstring explaining what the function does. Although it is not mandatory, documenting our code like this is good practice.
  3. return phrase == phrase[::-1]: This line checks if the phrase is equal to its reverse. If they are the same, it returns True; otherwise, it returns False.

Testing Our Function

To see our function in action, we’ll test it with two examples: one palindrome and one non-palindrome.

def is_palindrome(phrase: str) -> bool:
"""Check if phrase is a palindrome.

:param phrase: The phrase to check if it is a palindrome.
:return: `True` if the phrase is a palindrome.
"""
return phrase == phrase[::-1]

palindrome = "EYE"
not_palindrome = "EYE DOCTOR"

print(is_palindrome(palindrome))
print(is_palindrome(not_palindrome))

When you run this script, it will check both strings and print whether each is a palindrome.

$ python your_file.py
True
False

Making It Interactive

Instead of hardcoding the phrases, we’ll modify the script to allow user input. We’ll use the argparse module for this. This module is a tool for building command-line interfaces. Read more about it in the argparse documentation. You can explore other options, such as the input() function and more details in Python documentation.

Setting Up argparse

First, import the argparse module at the beginning of your file:

import argparse

Python Entry Point

A Python script usually has an entry point where execution starts. This is conventionally done using:

if __name__ == "__main__":
# Our code goes here.

With argparse, we modify it as follows:

if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Palidrome checker.")

PHRASE_HELP = "The phrase to check if it is a palindrome"
parser.add_argument("phrase", type=str, help=PHRASE_HELP)

args = parser.parse_args()
main(args.phrase)

Here, we create a parser object, define what arguments it should expect, and then run themain function with these arguments.

The Main Function

The main function will take the user input and use our is_palindrome function to check it.

def main(phrase: str) -> None:
"""Palindrome checker main function.

:param phrase: The phrase to check if it is a palindrome.
"""
if is_palindrome(phrase):
print(f"The phrase {phrase} is a palindrome.")
else:
print(f"The phrase {phrase} is NOT a palindrome.")

Line-by-line explanation:

  1. def main(phrase: str) -> None: The main function is defined. It takes one parameter phrase and does not return anything (None).
  2. Docstring: Similar to our previous function, we also have a docstring here.
  3. Checking the Palindrome: Inside the function, we use an if-else statement. This is how we make decisions in programming. The statement checks if the phrase is a palindrome. If it is, we print a message stating so. Otherwise, we print that the phrase is not a palindrome.

Final Implementation

Now that we’ve gone through each part, here’s what our complete script looks like:

"""Palindrome checker."""
import argparse


def is_palindrome(phrase: str) -> bool:
"""Check if phrase is a palindrome.

:param phrase: The pharse to check if it is a palindrome.
:return: `True` if the phrase is a palindrome.
"""
return phrase == phrase[::-1]


def main(phrase: str) -> None:
"""Palindrome checker main function.

:param phrase: The phrase to check if it is a palindrome.
"""
if is_palindrome(phrase):
print(f"The phrase {phrase} is a palindrome.")
else:
print(f"The phrase {phrase} is NOT a palindrome.")


if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Palidrome checker.")

PHRASE_HELP = "The phrase to check if it is a palindrome"
parser.add_argument("phrase", type=str, help=PHRASE_HELP)

args = parser.parse_args()
main(args.phrase)

Running the Program

To run the program, you’ll need to use the command line. Here’s a quick guide:

To see the instructions on how to use the program, type:

$ python easy/palindrome_checker.py --help
usage: palindrome_checker.py [-h] phrase

Palidrome checker.

positional arguments:
phrase The phrase to check if it is a palindrome

options:
-h, --help show this help message and exit

Here, the output details how to use the script, indicating that we need to supply a phrase as an argument.

Run the script with the phrase to test if a specific phrase is a palindrome. For example:

$ python easy/palindrome_checker.py "EYE"
The phrase EYE is a palindrome.

$ python easy/palindrome_checker.py "EYE DOCTOR"
The phrase EYE DOCTOR is NOT a palindrome.

Test Your Skills

Now, challenge yourself to improve the is_palindrome function to ignore spaces, punctuation, and case sensitivity. Here are a few test cases:

Palindromes:

"A man, a plan, a canal, Panama"
"Madam, in Eden, I'm Adam"
"Was it a car or a cat I saw?"
"No lemon, no melon"
"Racecar"

Non-palindromes:

"This is not a palindrome"
"Hello, world!"
"Python is fun"
"Medium is a great platform!"
"Is this a palindrome?"

Solution

Further Reading

If you want to learn more about programming and, specifically, Python and Java, see the following course:

Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.

--

--