How to check a palindrome number by Python

Profile Picture

saxenadivya859

Friday, 2024-08-02




Python Development Environment - Raspberry Valley


To check if a number is a palindrome, you need to determine if it reads the same forwards and backwards. Here's a step-by-step guide to do this:


  1. Convert the Number to a String: This makes it easier to compare individual digits. For example, if the number is 12321, convert it to the string "12321".
  2. Reverse the String: Create a reversed version of the string. For "12321", the reversed string will also be "12321".
  3. Compare the Original and Reversed Strings: If the original string and the reversed string are the same, then the number is a palindrome. If they are different, then it is not.


Code:

def is_palindrome(number):
    # Convert the number to a string
    num_str = str(number)
    
    # Reverse the string
    reversed_str = num_str[::-1]
    
    # Check if the original string is equal to the reversed string
    return num_str == reversed_str

# Example usage
print(is_palindrome(12321))  # True
print(is_palindrome(12345))  # False


How did you feel about this post?

😍 🙂 😐 😕 😡