Check If Input Number is Palindrome in Python

There are some numbers in mathematics when even reversed remain the same. Well as for observing these numbers with human eyes we don’t need to exert too much stress on our brains. However, to find the same thing using a computer program is quite a challenge for newbie programmers. Such numbers when even reversed remain the same are known as Palindrome numbers. And in today’s article, we’ll try to find Palindrome numbers using programs. So let’s find out how to Check If the Input Number is Palindrome or not in Python.

 

What’s The Approach?

 

  • The simplest approach we will apply is to reverse the given input number and check if it is equal to the original number.

 

  • Let’s consider input number n. Therefore if the reverse of n is similar to n we’ll print true otherwise we’ll print false.

 

  • We will create a separate function to return the reverse of input n.

 

  • Create a reverse variable rev_num, we will multiply it by 10 & perform a modulo operation with 10.

 

  • The above instructions will keep executing till the value of num is greater than 0. So after that, we’ll divide num with 10. This way we’ll get the trailing digit of input n becoming the leading digit in our reverse variable.

 

Also Read: Check Armstrong Number using Python

 

Python Program To Check If Input Number is Palindrome

 

Input:

N=2002

Output:

Is 2002 a Palindrome number? -> true

 

# Python program to check a
# number is Palindrome or not.

# Iterative function to reverse
# digits of num
def reverseDigits(num) :

    rev_num = 0;
    while (num > 0) :
        rev_num = rev_num * 10 + num % 10
        num = num // 10
    
    return rev_num

# Function to check if n is Palindrome
def isPalindrome(n) :

    # get the reverse of n
    rev_n = reverseDigits(n);

    # Check if rev_n and n are same or not.
    if (rev_n == n) :
        return 1
    else :
        return 0

# Driver Code
if __name__ == "__main__" :

    
    n = 2002
    
    if isPalindrome(n) == 1 :
        print("Is", n, "a Palindrome number? ->", True)
        
    else :
        print("Is", n, "a Palindrome number? ->", False)

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

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