Question 13 of 13intermediate🔧 ApplyLong Answer5 marks

Write a function that checks whether an input number is a palindrome or not. [Note: A number or a string is called palindrome if it appears same when written in reverse order also. For example, 12321 is a palindrome while 123421 is not a palindrome]

Correct Answer

A palindrome is a number that remains the same when its digits are reversed. For example, 12321 is a palindrome while 123421 is not.

To check for a palindrome, we need to reverse the number and compare it with the original number. If both are equal, the number is a palindrome.

Python Program: python def is_palindrome(num): original = num reverse = 0 while num > 0: digit = num % 10 reverse = reverse * 10 + digit num = num // 10 if original == reverse: return True else: return False

num = int(input("Enter a number: ")) if is_palindrome(num): print(num, "is a palindrome") else: print(num, "is not a palindrome")

The function is_palindrome() takes a number as input. It stores the original number in a variable. Using a while loop, it extracts each digit using modulo operator (%) and builds the reverse number. The loop continues until the number becomes 0. Finally, the function compares the original number with the reversed number. If they are equal, it returns True indicating the number is a palindrome; otherwise, it returns False.

Sample Output: Enter a number: 12321 12321 is a palindrome

Exercise: PROGRAMMING EXERCISES | Q: 8
For More Understanding

Explanation

The textbook defines a palindrome as a number or string that appears the same when written in reverse order. The solution follows the standard approach of reversing the number digit by digit using modulo and integer division operations, then comparing with the original. This is consistent with the programming style shown in other examples in the context like Program 6-14 (prime number check) and Program 6-19 (factorial).

Solution Steps

  1. Step 1: Define a function is_palindrome() that accepts a number

  2. Step 2: Store the original number in a variable

  3. Step 3: Use while loop to reverse the number by extracting digits using % and // operators

  4. Step 4: Compare original number with reversed number

  5. Step 5: Return True if equal (palindrome), False otherwise