Python program to check whether the inputted string is a Palindrome or not - Codicaly

 In this post, we are going to check whether an inputted string is a Palindrome or not.

What is Palindrome ?

             A Palindrome is a word, number, phrase, or other sequence of characters that reads the same backward as forward, such as madam or racecar. That means if the reverse of the inputted string is the same as that of the original, it is Palindrome otherwise not.

Pre-requisites :

  • Python Basics
  • Strings concept
  • Conditional statements.

Program :

a=input('Enter the phrase : ')
reverse=a[::-1]
if (reverse==a):
    print(a,'is a pallindrome')
else:
    print(a,'is not a pallindrome')












Explanation :




1. First we need to input the word for which we need to check it is a Palindrome or not. Using the input function we are inputting the phrase. Here we are not specifying anything before input like int or float. Hence it would take as a string that is the default.




2. To check we need to compare the reverse of the phrase with the original. Here we are creating the reverse of the inputted phrase and assigning it to reverse. We are using the string slicing method for reversing. The third argument is the step value. If the first two arguments are left like this and the step value is given as -1, it will return the reverse of the given string. If the inputted string is 'maths', it will return 'shtam'.





3. Now we created the reverse and have the original. We need to compare whether the reverse is the same as the original(a). For comparing we are using a comparison operator equal to (==). This returns true only when the L.H.S is the same as R.H.S. This is the condition. We are using 'if statement' for proceeding with other steps. If statement only proceeds when the 'if condition' is true.  




4. As from the indentation, we know that it is under the if statement. This statement only proceeds if the 'if condition' is true. If the reverse of the phrase and original phrase is the same, 'if condition' is true. If that is true, then the inputted phrase is Palindrome. We are printing them using the print statement.




5. This else statement proceeds only when the ' if condition' fails. 





6. As due to indentation, we know that it is under the else statement. If the reverse of the inputted string is not as same as the original phrase. Then the if statement fails. Now the else statement executes. Then, it will not be a palindrome. We are printing them using the print statement.

Input/Output :

For non-palindrome :

Non-Palindrome







For Palindrome :

Palindrome







Thank you 







Comments

Popular posts from this blog

Python Program to Print Fibonacci series - Codicaly

Python - Program to find the given number is a prime or composite number

Python Program To Print Average