Checking for a palindrome, using for-loop in Python and print output ONLY ONCE

Question:

I am fairly new to programming, so I hope you can help me.

I want to check if a input string is a palindrome. The palindrome-checker is case-insensitive.

Here is what I got so far:

# input word 
word = input("Enter a word: ")

# make it case-INsensitive
word = word.lower()

# we also need the length of word to iterate over its range
length_word = int(len(word))

### use a for-loop
for letter in range(len(word)):
    if word[-length_word] == word[-1]:
        print(word, "is a palindrome.")     
        
# if it doesn't match, its not a palindrome, print message
    else:
        print(word, "is not a palindrome.")

What bothers me is that it prints the phrase "is a palindrome." everytime. How can I fix it so it will only print it once if the word is a palindrome?

Thank you so much in advance!

Asked By: crey

||

Answers:

You just need to check the word against it’s reverse:

# input word 
word = input("Enter a word: ")

# make it case-INsensitive
word = word.lower()

# check word against it's reverse
if word == word[::-1]:
    print(word, "is a palindrome")
else:
    print(word, "is not a palindrome")
Answered By: ScottC

The classic way to do this is to compare your string with the inverted (reversed) representation of the same string. You could use loops to navigate over the string.

Here are 3 possible ways of achieving this. Note that the slice reverse approach is significantly faster than either of the other strategies.

from timeit import timeit

def ispalindrome_v1(s):
    return s == s[::-1]

def ispalindrome_v2(s):
    for i in range(len(s)//2):
        if s[i] != s[-(i+1)]:
            return False
    return True

def ispalindrome_v3(s):
    for c1, c2 in zip(s, reversed(s)):
        if c1 != c2:
            return False
    return True

S = 'aabbcdcbbaa'

for func in ispalindrome_v1, ispalindrome_v2, ispalindrome_v3:
    print(func.__name__, timeit(lambda: func(S)))

Output:

ispalindrome_v1 0.18437389799873927
ispalindrome_v2 0.6897212660005607
ispalindrome_v3 0.7656042110011185
Answered By: Cobra

The best way I can think of is ScottC’s, but I’ll endeavor to fix your own code:

Your main error is that you only compare the 1st and last letter of the word. You can fix it with:

 if word[index] == word[-1-index]: # I replaced "letter" with "index" (see Thierry's comment)

A secondary one is that the conclusion is written for each passage in the loop, instead of at the end. One way (amongst many others) to fix this is to add a counter of correct matches, and test if it fits the length of the word at the end of the code.

# input word 
word = input("Enter a word: ")

# make it case-INsensitive
word = word.lower()

# we also need the length of word to iterate over its range
length_word = len(word)

### use a for-loop
correct_matches = 0
for index in range(len(word)):
    if word[index] == word[-1-index]:
        correct_matches += 1
if correct_matches == length_word:
    print(word, "is a palindrome.")
else:
    print(word, "is not a palindrome.")

Note that it would be faster to only loop on the first half of the word.

Answered By: Swifty

Here is your code:

# input word 
word = input("Enter a word: ")

# make it case-INsensitive
word = word.lower()

# check word against it's reverse
print("is a palindrome: ", word == word[::-1])
Answered By: Divya Prakash
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.