Python Palindrome Program

Palindrome Program

A string or a number is said to be palindrome if its value remains the same when reversed.

Examples

  • Palindromes: peep, non, 12321, radar, level, etc.
  • Non-Palindromes: hello, 1234, radio, etc.

In the following examples, we check if the given string or number is palindrome or not, by using the following techniques.

  • Reverse the given string and check if it equals the original string.
  • Use a looping statement to compare the ith element from start with the ith element from end.

Check if Given String is Palindrome

In this example, we read a string from user, and check if this string is a Palindrome or not. We write a function isPalindrome() that takes a string as input, and returns True if the string is a Palindrome, or False if not.

Python Program

def isPalindrome(x):
    if (x == x[::-1]):
        return True
    else:
        return False

input1 = input('Enter string : ')
result = isPalindrome(input1)
if(result):
    print(input1, 'is a Palindrome.')
else:
    print(input1, 'is not a Palindrome.')

Output #1

Enter string : radar
radar is a Palindrome.

Output #2

Enter string : hello
hello is not a Palindrome.

Check if Given Number is Palindrome

In this example, we read a number from user, and check if this number is a Palindrome or not. We shall make use of the same function isPalindrome() that we defined above. Only additional step would be to convert the number read from user to a string.

Python Program

def isPalindrome(x):
    x = str(x)
    if (x == x[::-1]):
        return True
    else:
        return False

input1 = input('Enter number : ')
result = isPalindrome(input1)
if(result):
    print(input1, 'is a Palindrome.')
else:
    print(input1, 'is not a Palindrome.')

Output #1

Enter number : 1236321
1236321 is a Palindrome.

Output #2

Enter number : 1256321
1256321 is not a Palindrome.

Check if Given String is Palindrome using For Loop

In this example, we use For Loop to iterate over the characters and compare the ith character from start with the ith character from the end. If all the comparisons are an equal match, then the given string is a Palindrome.

Python Program

def isPalindrome(x):
    for i in range(0, int(len(x)/2)):
        if x[i] != x[len(x)-i-1]:
            return False
    return True

input1 = input('Enter string : ')
result = isPalindrome(input1)
if(result):
    print(input1, 'is a Palindrome.')
else:
    print(input1, 'is not a Palindrome.')

Output #1

Enter string : radar
radar is a Palindrome.

Output #2

Enter string : hello
hello is not a Palindrome.

Summary

In this Python Examples tutorial, we learned how to check if a given string or number is a Palindrome or not.