Palindrome Checker Program in Python

 

 

Palindrome Checker Program in Python

This document provides a Python program to check if a given number is a palindrome. A palindrome is a number that reads the same backward as forward.

Program Structure and Explanation

The program follows these steps:

  1. Accept input from the user.
  2. Convert the input to a string to facilitate easy reversal.
  3. Check if the reversed string is equal to the original string.
  4. Return the result.

Python Program

# Function to check if a given number is a palindrome
def is_palindrome(number):
    """
    Check if the provided number is a palindrome.
    
    Args:
    number (int): The number to check.
    
    Returns:
    bool: True if the number is a palindrome, False otherwise.
    """
    # Convert the number to string
    str_number = str(number)
    
    # Reverse the string and compare with the original
    if str_number == str_number[::-1]:
        return True
    else:
        return False

# Accept input from the user
try:
    num = int(input("Enter a number: "))
    # Check if the number is a palindrome and print the result
    if is_palindrome(num):
        print(f"{num} is a palindrome.")
    else:
        print(f"{num} is not a palindrome.")
except ValueError:
    print("Please enter a valid integer.")

Explanation of the Code

The function is_palindrome(number) is defined to check if the provided number is a palindrome. Here are the key parts of the function:

  • Args: The function takes one argument number, which is the number to check.
  • Convert to String: The number is converted to a string using str(number). This allows us to easily reverse the digits.
  • Reverse and Compare: The string is reversed using slicing str_number[::-1] and compared with the original string.
  • Return Result: The function returns True if the original string and reversed string are the same, indicating the number is a palindrome. Otherwise, it returns False.

The main part of the program:

  • Input: It accepts an integer input from the user.
  • Validation: It checks if the input is a valid integer using a try-except block to handle any ValueError.
  • Result: It calls the is_palindrome function and prints whether the number is a palindrome or not.

 

Leave a Reply

Your email address will not be published. Required fields are marked *