Python Program to Check if a String or Number is a Palindrome

In this tutorial, we will discuss Python program to check if a string or number is a palindrome.

Before going to the program first, let us understand what is a Palindrome Number.

Palindrome Number:

  • A palindrome is a sequence of characters that reads the same backward as forward.
  • For example, “madam” and “121” are palindromes.

Related: Python program to check if a number is an Armstrong number or not

Program code for checking if a string or number is a Palindrome in Python

# Palindrome Checker in Python
def is_palindrome(s):
    return s == s[::-1]

input_str = input("Enter a string or number: ")
if is_palindrome(input_str):
    print(f"{input_str} is a palindrome.")
else:
    print(f"{input_str} is not a palindrome.")

Explanation

  1. Function Definition: The is_palindrome function takes a string s as input and returns True if the string is a palindrome, and False otherwise.
  2. Check Palindrome: The function checks if the string is equal to its reverse using slicing.
  3. Main Program: The program prompts the user to enter a string or number and then checks if it is a palindrome using the is_palindrome function.

Output

Python Program to Check if a String or Number is a Palindrome

  • When you run the above program, it will prompt you to enter a string or number.
  • After entering the input, it will check whether the input is a palindrome or not and print the result.

Conclusion

  • In this tutorial, we learned how to check if a given string or number is a palindrome using a Python program.
  • Understanding this concept is essential for solving various mathematical problems and competitive programming challenges.
  • Practice this example to enhance your programming skills and understanding of palindromes.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *