ScanSkill

Check Palindrome Number in Python

In this, we'll write some example programs to check palindrome number in Python using different approaches.

This covers following approaches:

  • Check palindrome number in Python using while loop
  • Check palindrome number in Python using a user-defined function
  • Check palindrome number in Python using class

Palindrome Numbers:

A palindrome number is a number whose reverse is equal to the number itself. For example, the reverse of 1771 is equal to the number itself, therefore 1771 is a palindrome number. And 123 is not a Palindrome number, because its reverse 321 is not equal to the number itself.

Prerequisites

Check palindrome number in Python using while loop

This program asks the user to input a number. It checks whether the number is palindrome or not and print the result.

print("Enter the Number: ")
num = int(input())
reverse = 0
temp = num
while temp>0:
    rem = temp%10
    reverse = rem + (reverse*10)
    temp = int(temp/10)
if reverse==num:
    print("It is a Palindrome Number")
else:
    print("It is not a Palindrome Number")

Output:

Enter the Number: 
1212
It is not a Palindrome Number
Enter the Number: 
1221
It is a Palindrome Number

Check palindrome number in Python using function

In this approach, the function PalindromeOrNot() takes an argument and evaluates whether a number is a palindrome or not. The function is called after user input.

def PalindromeOrNot(n):
    reverse = 0
    temp = n
    while temp>0:
        rem = temp%10
        reverse = rem + (reverse*10)
        temp = int(temp/10)
    if reverse==n:
        print("It is a Palindrome Number")
    else:
        print("It is not a Palindrome Number")

print("Enter a Number: ")
num = int(input())

PalindromeOrNot(num)

Output:

Enter a Number: 
25752
It is a Palindrome Number
Enter a Number: 
25684
It is not a Palindrome Number

Check palindrome number in Python using Class

The same can be done with class method as follows:

class PalindromeChecker:
  def PalindromeOrNot(self, n):
    reverse = 0
    temp = n
    while temp>0:
        rem = temp%10
        reverse = rem + (reverse*10)
        temp = int(temp/10)
    if reverse==n:
        print("It is a Palindrome Number")
    else:
        print("It is not a Palindrome Number")

print("Enter a Number: ")
num = int(input())

obj = PalindromeChecker()
res = obj.PalindromeOrNot(num)

Here, all properties of the class named PalindromeChecker get assigned to an object named obj. Then the object can be used to access the member function of the class PalindromeOrNot using the dot (.) operator. (obj.PalindromeOrNot(num))

Output:

Enter a Number: 
121
It is a Palindrome Number
Enter a Number: 
25684
It is not a Palindrome Number

Conclusion

In this, we discussed how to Check palindrome number in Python using while loop, using function, and using class.