Ads by ProfitSence

Palindrome in Python Code Example

Last Updated on Wednesday 5th Oct 2022

What is a Palindrome?

Define Palindrome

A palindrome is a word or a number or a phrase or other sequence of characters which reads the same backward as forward.

  • Heres the word civic in reverse also, civic,it reads the same forward or backward right?, so it is a palindrome.
  • If we have the number 121, then when we reverse it, we can get 121, so it is a palindrome.

Check for Palindrome

  • Let us have user input in string form
					inp = input("Enter the Input: ")

  • Next thing that we need to reverse the user input.
  • For reverse, we have many techniques, but I use the slice and slice the given string.
					reverse = inp[::-1]

  • For Slicing the entire string, I'm not going to specify any starting and ending points.
  • -1 indicates that we want to step backward by 1, so it will reverse the string and return.
					if(inp === reverse):
  print("Yes,it is Palindrome")

  • We need to check the original value entered by the user is equal to the reverse of that value.
  • If it is equals, then it means then the input value is Palindrome

Example 1

					inp = input("Enter the Input: ")
reverse = inp[::-1]

if inp == reverse:
    print("Yes,it is Palindrome")

					# Enter the Input: civic
# Yes, it is Palindrome

# Enter the Input: abcdef
# No, It is not


Example 2

					def palindrome():
    x = input("Enter a string: ")
    y = x[::-1]
    if x == y:
        print("It is a palindrome")
        print("Not a palindrome")

					# Enter a string: level
# It is a palindrome