Improving Python Palindrome code

steve picture steve · Oct 14, 2013 · Viewed 22.4k times · Source

So I recently implemented a code that checks a word to see if it's a palindrome.

def isPalindrome():
    string = input('Enter a string: ')
    string1 = string[::-1]
    if string[0] == string[(len(string)-1)] and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
            print('It is a palindrome')
    else:
        print('It is not a palindrome')
isPalindrome()

I was wondering if anyone could give me tips on simplifying the code.

Edit - If I were to make the function an iterative function with the statements string == string1, how would I stop the endless while loop? Would I need a count to stop the while loop?

Answer

TerryA picture TerryA · Oct 14, 2013

No need for such complex conditional. You already have a reversed string (string[::-1]).

All you need to do is this:

def isPalindrome():
    string1 = input('Enter a string: ')
    string2 = string1[::-1]
    if string1 == string2:
        return 'It is a palindrome'
    return 'It is not a palindrome'

isPalindrome()

(by the way don't use string as a variable name. That's the name of a built-in module)

It's better to return the strings instead of printing them. That way your function will not return None (preventing some stuff that could happen later)