The task is to create a Python function that checks whether a given string or number is a palindrome. A palindrome is a sequence that reads the same backward as forward, such as “madam” or the number 121.
The function should handle both strings and integers, returning a boolean value indicating whether the input is a palindrome.
Implementation
def is_palindrome(value):
# Convert the input to string to handle both strings and numbers
str_value = str(value)
# Check if the string is equal to its reverse
return str_value == str_value[::-1]
# Example usage
print(is_palindrome("madam")) # Output: True
print(is_palindrome(121)) # Output: True
print(is_palindrome("hello")) # Output: False
print(is_palindrome(12321)) # Output: True
The is_palindrome
function begins by accepting a parameter named value
, which can be either a string or a number. The function then converts the input into a string using str(value)
. This allows us to handle both types seamlessly.
Next, the function checks if the string representation of the input is equal to its reverse. The slicing operation str_value[::-1]
is a concise way to reverse a string in Python.
If the original string matches its reversed version, the function returns True
, indicating that the input is a palindrome. Otherwise, it returns False
.