Write a python program to accept a number from the user and check whether it is a palindrome or not.

Python Program: Palindrome Number Checker

Palindrome Checker Mathematical Logic

Python Code
num = int(input("Enter a number: "))
rev = 0
temp = num

while temp > 0:
    digit = temp % 10
    rev = (rev * 10) + digit
    temp //= 10

if num == rev:
    print("It is a Palindrome Number")
else:
    print("It is NOT a Palindrome Number")
Step-by-Step Explanation
1. Taking User Input: num = int(input(...)) takes input from the user and converts it to an integer.
2. Initializing Variables: rev = 0 stores the reversed number, while temp = num retains a copy to modify inside the loop.
3. The While Loop: while temp > 0 continues extracting digits until temp reaches 0.
4. Extracting the Last Digit: temp % 10 retrieves the last digit of the number.
5. Reversing the Number: rev = (rev * 10) + digit shifts existing reversed digits to the left and appends the new digit.
6. Dropping the Last Digit: temp //= 10 performs floor division to drop the processed last digit.
7. Comparing Results: The if num == rev: statement checks if the original input matches the constructed reversed number.
Worked Example: Input = 121

Initial State: num = 121, rev = 0, temp = 121

Iteration temp % 10 (digit) rev = (rev * 10) + digit temp //= 10 (Remaining)
1 121 % 10 = 1 (0 * 10) + 1 = 1 121 // 10 = 12
2 12 % 10 = 2 (1 * 10) + 2 = 12 12 // 10 = 1
3 1 % 10 = 1 (12 * 10) + 1 = 121 1 // 10 = 0 (Loop ends)

Comparison: num (121) == rev (121)True

Final Output: It is a Palindrome Number

Leave a Comment

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

Scroll to Top