Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

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”.

Join the conversation