Check if a Number or String is Palindrome in Python

In this blog, we will write a Python program to check if a number or string is a palindrome and learn its operation. We will also delve into the concept of palindromic numbers and present a Python program that checks whether a given number or string is a palindrome or not.

What is a palindrome number?

A palindrome number is a number that remains the same when its digits are reversed. For example, 121, 1331, and 98789 are all examples of palindrome numbers. They exhibit a unique symmetry, which makes them intriguing to mathematicians and computer scientists alike. From number theory to programming, palindrome numbers present interesting challenges and opportunities for exploration.

Python Program to Check a Number is Palindrome Using Loop

# Python Program To Check A Number Is Palindrome or not

# we are taking a number from user as input
# entered value will be converted to int from string
n = int(input("Enter any number: "))

# integer is stored in another temporary variable
temp = n
rn = 0

while n>0:
    r = n % 10
    rn = rn * 10 + r
    n = n // 10
    
if rn == temp:
    #If both are equal, the number is a palindrome.
    print("The number is Palindrome") 
else:
    #If both aren’t equal, the number isn’t a palindrome.
     print("The number is not Palindrome")

Code Explanation

  • Asking the user to Input a number

We start the program by prompting input from the user, which is the number to be checked for palindrome.

  • Convert input to Integer

We convert the input number, which is initially in string format, to an integer using the int() function. This is done to perform mathematical operations on the number. Next, we create a temporary variable temp and assign the input number to it and compare the reversed number with the original number later.

  • Initialise variables and Reverse the number

We initialise a variable rn (reversed number) as 0 to store the reversed version of the input number. We enter a while loop that continues as long as the number (n) is greater than 0. 

In each iteration, we extract the last digit of the number by calculating the remainder when dividing it by 10 and multiply the reversed number (rn) by 10 and add the extracted digit to it. Then, the number is updated by removing the last digit using integer division.

  • Checking for palindromes

After the while loop ends, the reversed number is stored in rn and we compare the reversed number (rn) with the original number stored in the temporary variable (temp).

If both numbers are equal, it means the input number is a palindrome.

If they are not equal, it means the input number is not a palindrome.

  • Printing the result

Depending on the comparison result, the program prints either “The number is Palindrome” or “The number is not Palindrome” to indicate whether the input number is a palindrome or not.

Output:

Case 1: If the number is a palindrome, the output will be:

If the number is 1221

Enter any number: 1221
The number is Palindrome

Case 2: If the number is not a palindrome, the output will be:

If the number is 1451

Enter any number: 1451
The number is not Palindrome

In this program, when the user inserts: 1221 the program proceeds to check whether the number is a palindrome or not. Since the reversed number (1221) is equal to the original number (1221), the program prints “The number is Palindrome” to indicate that the input number is indeed a palindrome.

But, when the number 1451 is inserted, the program finds that the reversed number (1451) is not equal to the original number and it would print “The number is not Palindrome” to indicate that the input number is not a palindrome.

Python Program to Check a String is Palindrome Using Loop

# take input from the user
string = input("Enter a string: ")

# initialize two pointers, one at the start and one at the end of the string
start = 0
end = len(string) - 1

# flag to keep track of whether the string is a palindrome or not
is_palindrome = True

# loop until the pointers meet or cross each other
while start < end:
    # compare the characters at the current pointers
    if string[start] != string[end]:
        # if characters don't match, set the flag to False and break the loop
        is_palindrome = False
        break
    
    # move the pointers towards each other
    start += 1
    end -= 1

# check the flag to determine if the string is a palindrome or not
if is_palindrome:
    print("The string is a palindrome.")
else:
    print("The string is not a palindrome.")

Code Explanation

  • Take input from the user
  • Initialize two pointers, one at the start and one at the end of the string
  • Flag to keep track of whether the string is a palindrome or not
  • Loop until the pointers meet or cross each other
  • Compare the characters at the current pointers
  • If characters don’t match, set the flag to False and break the loop
  • Move the pointers towards each other
  • Check the flag to determine if the string is a palindrome or not
  • Print the result

Output:

Case 1: If the string is a palindrome, the output will be:

If the number is MOM

Enter any number: MOM
The string is Palindrome

Case 2: If the string is not a palindrome, the output will be:

If the number is TEXT

Enter any number: TEXT
The string is not Palindrome

Following methods to check for Palindromes

Alternatively, we can use the following methods to check for Palindromes:

  • String Reversal: We can convert the number to a string and reverse it using slicing or the [::-1] notation. Now, compare the reversed string with the original string to check for palindrome.
  • Recursive Method: Define a recursive function that checks for palindrome.
  • Base case: If the number has only one digit or is 0, it is considered a palindrome.
  • Recursive case: Check if the first and last digits are equal, and recursively call the function on the remaining digits.

In our program, we used a while loop as it is efficient and has a lower time complexity compared to the string reversal and recursive approaches. It directly manipulates the number by extracting digits and reversing them without the need for string conversions or recursive function calls. It also requires less code and is easier to understand for beginners. However, If code simplicity or the need for string manipulation arises, you might consider alternative methods.

In this Python program, we demonstrated an efficient approach to determine if a given number remains the same when its digits are reversed. By leveraging the concept of modulus and integer division, the program successfully checks for palindromic properties. It effectively showcases the iterative nature of checking for palindromes, using a while loop to extract the last digit of the number and build the reversed number. 

This program can be easily integrated into larger projects or used as a standalone solution. Understanding the logic and operation behind this code provides a solid foundation for exploring and implementing recursion-based approaches to solve similar problems. It serves as a stepping stone for aspiring programmers to deepen their understanding of Python and develop more complex applications in the future.

FAQs – The number is Palindrome or Not in Python

What is the purpose of the temporary variable ‘temp’?

The ‘temp’ variable stores the original input number. It is used to compare with the reversed number at the end of the program to determine if the number is a palindrome.

How does the program handle negative numbers or decimals?

The program assumes that the user will input only positive integers. Negative numbers and decimals are not considered palindromes in this program.

What happens if I enter a non-numeric value?

The program expects a numeric input. If a non-numeric value is entered, it will raise a ValueError and the program will terminate.

Can I use this program to check if a word is a palindrome?

No, this program is specifically designed to check if a number is a palindrome. To check if a word is a palindrome, you would need to modify the program to compare characters instead of digits.

How can I modify the program to check for a palindrome in a different number system, such as binary or hexadecimal?

To check for palindromes in different number systems, you would need to convert the input number to the desired number system and then compare it with its reversed form in that number system.

About The Author

Leave a Reply