简体   繁体   中英

How can I make sure a word is palindrome using Python while using recursion?

I am trying to create a code in which python asks the user for input or a word and it has to check whether it's a palindrome or not using recursion. If the word is not a palindrome through the reverse() function it will take in the string and, through recursion, return that string in reverse. It seems that I am able to take input and when I put in a word that's not a palindrome it gives me back the output needed. However it doesn't give back the word in reverse and also when I put a word that is a palindrome and it doesn't give the input back leaving a blank space in the output.

def reverse(choice, index, new_word):
    if index < 0:
        return new_word
    else:
      new_word += choice[index]
      return reverse (choice, index - 1, new_word)

def palindrome():
    new_word = ""
    choice = input("Please enter a word to check if it is palindrome:")
    result = reverse(choice, len(choice) - 1, new_word)

    if result == choice:
        print("That word",choice,"IS a palindrome")
    else:
        print("Sorry,",new_word,"is NOT a palindrome")

palindrome()

This is happening because you have set new_word to an empty string, and then you're taking the result of reverse() and storing that in another variable called result .

This should fix your issue:


def palindrome():
    new_word = ""
    choice = input("Please enter a word to check if it is palindrome:")
    result = reverse(choice, len(choice) - 1, new_word)

    if result == choice:
        print("That word",choice,"IS a palindrome")
    else:
        # change here to result
        print("Sorry,",result,"is NOT a palindrome")

Alternatively, you can use choice[::-1] to reverse a string. it is cleaner and you don't have to use recursion. However, the above fix will help you with the recursion bit as well.

Try the following:

def check_palindrome(word): # Creating function with 1 parameter: word
    if word == word[:: -1]: # word[:: -1] reverses a string
        return True # Return a true value if word is the same when reversed
    else:
        return False # Otherwise, return a false value


print(check_palindrome("racecar"))  # Palindrome
print(check_palindrome("hello world"))  # Not a palindrome

the syntax word[:: -1] reverses the word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM