Palindrome In Python
What is Palindrome?
A Palindrome can be defined as the number or a string that resides unchanged when it is reversed.
Example: 14341
Output: Yes, this is a Palindrome number
Example: RACECAR
Output: Yes, this is a Palindrome string
Palindrome Program using While Loop
We can find Plaindrome with the use of while loop. It is very easy to find Palindrome using while loop.
Example:
num=int(input("Enter a number:"))
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("This number is a palindrome!")
else:
print("This is not a palindrome!")
Output:
Enter a number:454
The number is a palindrome!
Using built-in Functions
Now we are checking the string whether it is a palindrome or not by using the built-in functions.
Example: Palindrome Program using inbuilt Method.
string=input(("Enter a string:"))
if(string==string[::-1]):
print("This string is a palindrome")
else:
print("This string is not a palindrome")
Output:
Enter a string: ABCDCBA
This string is a palindrome
Explanation: In the above program, we have checked that the string is palindrome or not. Here, we have taken the input from the user by using the input method and then used the slicing operation for checking whether the string is reversed or not. Then we have printed the result.
Using recursive function
Here, we are using the recursive function for checking if a string is palindrome or not.
Example:
# python code for checking Palindrome
# using recursion
def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
print("This string is a palindrome!")
else:
print("This string isn't a palindrome!")
Output:
Enter string:malayalam
This string is a palindrome!
Explanation: In the above code, we have used a recursive function for checking a string is palindrome or not.
Using for loop
Here, we are using for loop for checking the numbers whether it is palindrome or not.
Example:
number=input("Enter any number :")
i=0
for i in range(len(number)):
if number[i]!=number[-1-i]:
print('This is not a palindrome')
break
else:
print('This is a palindrome')
break
Output:
Enter any number:7667
It is a palindrome
Explanation: In the above code, we have created a for loop in the program for checking the numbers are palindrome or not.
Conclusion
In the above article, we have discussed different methods for checking the palindrome numbers and a string. Now, you have understood the concept of palindrome in Python.