Palindrome
A string is a palindrome when it is the same when read backwards.
For example, the string "bob"
is a palindrome. So is "abba"
. But the string "abcd"
is not a palindrome, because "abcd" != "dcba"
.
Write a function named palindrome
that takes a single string as its parameter. Your function should return True
if the string is a palindrome, and False
otherwise.
Â
==== SOLUTION ====
You can implement the `palindrome` function in Python by checking if the string is equal to its reverse. Here’s how you can do it:
“`python
def palindrome(s):
     # Check if the string is equal to its reverse
     return s == s[::-1]
# Test the function
print(palindrome(“bob”)) # Output: True
print(palindrome(“abba”)) # Output: True
print(palindrome(“abcd”)) # Output: False
“`
Explanation:
1. `def palindrome(s):`: This line defines a function named `palindrome` that takes a single parameter `s`, which is a string.
2. `return s == s[::-1]`: This line returns `True` if the string `s` is equal to its reverse (`s[::-1]`). The `[::-1]` slice notation reverses the string.
So, when you call `palindrome(“bob”)`, it returns `True` because the string “bob” is the same when read backwards. Similarly, for `”abba”`, it returns `True` because “abba” is also a palindrome. However, for `”abcd”`, it returns `False` because “abcd” is not the same as its reverse “dcba”.