Contents
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.
Examples
1. Check if given string is a Palindrome
In this example, we take a string literal in variable s, 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(s):
if (s == s[::-1]):
return True
else:
return False
s = 'radar'
result = isPalindrome(s)
if(result):
print(s, 'is a Palindrome.')
else:
print(s, 'is not a Palindrome.')
Run Code CopyOutput #1
radar is a Palindrome.
2. Check if given number is a Palindrome
In this example, we take a number in variable n, 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 to a string.
Python Program
def isPalindrome(n):
n = str(n)
if (n == n[::-1]):
return True
else:
return False
n = 1236321
result = isPalindrome(n)
if(result):
print(n, 'is a Palindrome.')
else:
print(n, 'is not a Palindrome.')
Run Code CopyOutput #1
1236321 is a Palindrome.
3. Check if given string is a 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(s):
for i in range(0, int(len(s)/2)):
if s[i] != s[len(s)-i-1]:
return False
return True
s = 'radar'
result = isPalindrome(s)
if(result):
print(s, 'is a Palindrome.')
else:
print(s, 'is not a Palindrome.')
Run Code CopyOutput #1
radar is a Palindrome.
Summary
In this Python Examples tutorial, we learned how to check if a given string or number is a Palindrome or not.