Python Program to check the number is Palindrome


May 10, 2022, Learn eTutorial
1412

In this simple python program, we need to check the number is a palindrome number. It's a number-based python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is a palindrome number?

In this basic python program, we have to check for palindrome numbers. A palindrome number is a number in which the number will be the same when it is reversed. For example, let us take the number 121 and check that it is palindrome or not. To achieve that, we have to reverse the given number and check both the number and reverse are the same.

  • Number: 121
  • Reverse: 121
What is a palindrome

Both are the same, and the number is a Palindrome. 

How to check the number is a palindrome in python?

To apply that logic in the python program, we have to save the number to a temp variable, then use a while loop in python till the number is zero and reverse the number using 3 steps; firstly, we use the mod operator to take one digit from the number and add the digit we got from the mod operator and remove one digit from the number by dividing the number by 10. Finally, we have to compare the number with the reverse of the number using an if condition in python language, and if that condition is satisfied, print its palindrome. Else print, not palindrome using python language syntax.

ALGORITHM

STEP 1: Accept the user's input and convert that to an integer using int in the python programming language.

STEP 2: Assign the value of the number to a temporary variable. And initialize the rev variable to zero to store the value of the reversed number.

STEP 3: Use the while loop until the number is greater than zero

STEP 4: Use the mod operator to extract one digit from the number.

STEP 5: Add the digit with the reversed variable which is multiplied by 10, [we did the multiplication with 10 to place the digit in the proper location of the number]

STEP 6: Remove one digit from the number by dividing the number by 10.

STEP 7: Use an if condition to check the temp variable, and the reverse variable is the same. Suppose that is the same, print palindrome else, not palindrome using python programming basics.

Python Source Code

                                          n=int(input("Enter number:"))

temp=n       # save the number in temporary variable

rev=0

while(n>0):

    dig=n                # reversing the number using while loop

    rev=rev*10+dig

    n=n//10

if(temp==rev):              # check the temp and reverse are same

    print("The number is a palindrome")

else:

    print("The number isn't a palindrome")
                                      

OUTPUT

Enter number: 181

The number is a palindrome