In this post we shall learn how to find whether given number is a palindrome or not using python language.We have already seen palindrome program in C,C++,Java.By definition a number is called as palindrome if the reverse of the number is same as the original.
To find the reverse of the number we need to use ‘/’ and ‘%’ operators.The result of the ‘/’ is the quotient of the division and result of ‘%’ is the remainder of the division.But which number should be used to divide the given number.We use 10 for the division operation.The vital part of the code is:
while(temp>0) remainder = temp % 10 temp = temp / 10 reverse = reverse *10 + remainder
Explanation:Consider that the given number is 142.Now that number is copied to temp variable.While loop checks the temp variable.If the value is greater than 0 then it can enter the loop.
In the loop, the remainder of the % operation is stored in remainder.i.e 142% 10 gives 2 as remainder.The ‘/’ operator gives the quotient of division and it is stored in temp.i.e 142/10 gives 14 and stores it in temp variable.
Before to the loop the reverse variable is initialized to the 0.Now that 0*10+2 = 2 is stored in reverse variable.In this way loop is iterated till the condition is failed.
n = input("\nEnter any number to check for palindrome:") temp = n remainder = reverse = 0 while (temp > 0) : remainder = temp % 10 temp = temp / 10 reverse = reverse *10 + remainder if(int(n) == reverse) : print "\n\t\tGiven number " +str(n)+" is palindrome" else : print "\n\t\tGiven number " +str(n)+" is not a palindrome"