Write a python program to check Palindrome number using object oriented approach
The Python program, PalindromeChecker, is designed to check whether a given number is a palindrome. Here's an explanation of how the program works:
- class PalindromeChecker: This is a class that defines a palindrome checker. It has two methods:
- __init__(self, num): This is the constructor method that initializes the object with a number num.
- is_palindrome(self): This method checks if the number is a palindrome. It does this by first converting the number to a string (num_str). Then, it reverses the string using slicing (reversed_str = num_str[::-1] ) and checks if the reversed string is equal to the original string. If they are equal, it returns True, indicating that the number is a palindrome; otherwise, it returns False.
- num = int(input("Enter a Number : ")): This line of code prompts the user to enter a number, and it converts the user's input to an integer, which is stored in the num variable.
- checker = PalindromeChecker(num): This line creates an instance of the PalindromeChecker class with the number entered by the user. The num value is passed as an argument to the constructor, initializing the num attribute of the checker object.
- if checker.is_palindrome():: This conditional statement checks whether the is_palindrome method of the checker object returns True. If it does, it means the entered number is a palindrome, and it prints a message indicating that the number is a palindrome. Otherwise, it prints a message indicating that the number is not a palindrome.
- The program then either prints "{num} is a Palindrome Number" or "{num} is not a Palindrome Number" based on the result of the is_palindrome method.
Here's how the program works:
- The user is prompted to enter a number.
- The program creates an instance of the PalindromeChecker class with the entered number.
- It checks whether the entered number is a palindrome using the is_palindrome method.
- Depending on the result, it prints a message indicating whether the number is a palindrome or not.
This program demonstrates the concept of using a class to encapsulate functionality for checking if a number is a palindrome, making the code more organized and reusable.
Source Code
class PalindromeChecker:
def __init__(self, num):
self.num = num
def is_palindrome(self):
num_str = str(self.num)
reversed_str = num_str[::-1] # Reverse the string
return num_str == reversed_str # Check if the reversed string is equal to the original string
num = int(input("Enter a Number : "))
checker = PalindromeChecker(num)
if checker.is_palindrome():
print(f"{num} is a Palindrome Number")
else:
print(f"{num} is not a Palindrome Number")
Output
Enter a Number : 12321
12321 is a Palindrome Number