Example 5: Palindromes

Palindrome is a word or phrase such as ‘deed’ or ‘level’, which is the same when you spell it backwards. The following program determines whether a word is palindrome.

# 02Loops example_05 Palindromes1.py
# determine whether a word input is a palimdrome

word = raw_input("Enter a word: ")

revWord = ""                                #start reversed word as blank
x = len(word) - 1                           #find the length of the input word

for i in range(x,-1,-1):                    #start at end of word & move backwards
    letter = word[i]                        #get the letter
    revWord = revWord + letter              #add it to end of revWord

print "The original word was",word
print "The reversed word is",revWord

if (word == revWord):                  #check if the original word is same as reversed word
        print word,"is a palindrome"
else:
        print word,"is not a palindrome"

For example, when we input “apple”, the output is:

Enter a word: apple
The original word was apple
The reversed word is elppa
apple is not a palindrome

When we input “level”, the output is:

Enter a word: level
The original word was level
The reversed word is level
level is a palindrome

In Python, there exists another way to reverse a string. Try the following

>>> ‘foobar'[::-1]

‘raboof’

Hence, we can write the following program:

# 02Loops example_05 Palindromes2.py
# determine whether a word input is a palimdrome

word = raw_input("Enter a word: ")

revWord = word[::-1]               # generate the reversed string using slicing
print "The original word was",word
print "The reversed word is",revWord

if (word == revWord):
        print word,"is a palindrome"
else:
        print word,"is not a palindrome"

In many languages, including Python, one task can be accomplished in a number of ways. Program Palindromes1 is the program that teaches students the logic needed to reverse a string in an iterative way.  Program Palindromes2 uses what Python calls “slicing” of strings. An introductory course would not teach slicing, but a few students are likely to find it. When giving students an assignment, it can be a good idea to state what libraries and features the students can and cannot use in their program.