Search code examples
pythonstringpalindrome

Palindrome Coding issue


Writing a program:

  1. Input string from the user
  2. print out whether this string is a palindrome or not

Also, I found a few other codes online but want to work with this code only.m Please let me know the error

i = str(input())

for item in i:
  print(item)

  if int(i[item]) == int(i[-item]):
    print('yes')
  else:
    print('no')

Solution

  • Although for item in i: loops through every character in the string, there are several problems with your code line if int(i[item]) == int(i[-item]):. First of all, item is going to be a character from your string. So if the user types "hello", then i[item] first looks for i['h']. Since 'h' is a character and not a number, this makes Python think that i is a dictionary and not a string, and thus tells Python to look for a dictionary named i and return the value where the key is h. That won't work since i is your original string, not a dictionary.

    It looks like what you meant to do here is compare i[0] (the first character in the string) to i[-1] (the last character in the string), then i[1] to i[-2], and so on. But even you if looped through the position numbers, i[-item] doesn't mathematically give you what you want.

    Yet another issue here is that you're checking each character one at a time and returning "yes" or "no". What you ultimately want though is to output one simple answer: whether your string is a palindrome or not.

    Also, there's no need to put str() around input(), since input returns a string anyway, even if the user enters only numerals. By the way, even though you're using i as your string variable, the usual convention in programming is to use i to denote some sort of integer, such as one you're iterating through in a for loop. But that's OK for now.

    As some of the other answers have shown, i[::-1] is a quick way to return the reverse of a string itself. So if you're OK with seeing the output return True if the string is a palindrome and False if it isn't, then here's an extremely simple way to do it:

    i = input()
    print(i == i[::-1])
    

    If the string i is identical to itself reversed, then i == i[::-1] returns True. If not, it returns False. The print statement then prints whichever the answer is.

    However, if you really do want to do it the long way, testing character by character in a loop, then here's one way to do it. You could make a function that takes in a string and does the work:

    def is_palindrome(mystring):
        # The "//2" here divides by 2 and ignores the remainder.  So if
        # there are an even number of letters, we'll test each pair.  If
        # It's an odd number, then we don't care about the middle character
        # anyway.  Compare [0] to [-1], then [1] to [-2], [2] to [-3], and so on.
        for position in range(0, len(mystring)//2):
            # If we've found a mismatched pair of letters, then we can
            # stop looking; we know it's not a palindrome.
            if mystring[position] != mystring[(-1 * position) - 1]:
                print("This is NOT a palindrome")
                return  # This breaks you out of the entire function.
    
        # If we've gotten this far, then the word must be a palindrome.
        print("This is a palindrome")
    
    
    # Here's where we run the command to input the string, and run the function
    mystring = input("Enter your string: ")
    is_palindrome(mystring)